IllegalArgumentException:参数 valuefunction.AggregationFunction 与预期类型不匹配 [java.lang.Long (n/a)]

IllegalArgumentException: Parameter valuefunction.AggregationFunction did not match expected type [java.lang.Long (n/a)]

我想通过条件生成器增加我的变量。我写了下面的代码

    final CriteriaBuilder cb= getCriteriaBuilder();
    final CriteriaUpdate<MyEntity> update = cb.createCriteriaUpdate(MyEntity.class);
    final Root<MyEntity> root = update.from(MyEntity.class);

    update.set("field", cb.sum(criteriaBuilder.<Long>sum(root.get("field"), 1L)));
    update.where(cb.equal(root.get("id"), id));

    final Query query = getEntityManager().createQuery(update);
    query.executeUpdate();

我的实体:

@Table(name ="myEntity")
@Entity
public class MyEntity{
private String id;
private long field;
}

数据库table具有以下结构:

  create table if not exists myEntity
(
    field integer not null,
    id varchar(32) not null,
);

但是我遇到了以下错误

java.lang.IllegalArgumentException: Parameter value [org.hibernate.query.criteria.internal.expression.function.AggregationFunction$SUM@46dd740b] did not match expected type [java.lang.Long (n/a)]

我该如何解决我的问题?

您的代码中存在多个错误。

第一:你select重载错误。

CriteriaUpdate<T> set(String attributeName, Object value);

而不是:

<Y> CriteriaUpdate<T> set(
        Path<Y> attribute,
        Expression<? extends Y> value);

这是因为您使用了未类型化的 CriteriaBuilder。解决它的方法是将第一个参数作为 Path<Long> 传递,而不是 String.

第二个: 我不确定您的查询要完成什么,但看起来总和为多。我相信它应该看起来像:

Path<Long> fieldPath = root.get("field");
update.set (fieldPath, cb.sum(root.get("field"), 1L));
update.where(cb.equal(root.get("id"), id));

这将生成:

update
    my_entity 
set
    field=field+1 
where
    id=?"