【问题标题】:IllegalArgumentException: Parameter valuefunction.AggregationFunction did not match expected type [java.lang.Long (n/a)]IllegalArgumentException:参数 valuefunction.AggregationFunction 与预期类型不匹配 [java.lang.Long (n/a)]
【发布时间】:2018-08-17 19:39:04
【问题描述】:

我想通过标准生成器增加我的变量。我写了以下代码

    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;
}

数据库表结构如下:

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

但是我遇到了以下错误

java.lang.IllegalArgumentException:参数值 [org.hibernate.query.criteria.internal.expression.function.AggregationFunction$SUM@46dd740b] 与预期类型不匹配 [java.lang.Long (n/a)]

我该如何解决我的问题?

【问题讨论】:

    标签: java postgresql hibernate hibernate-criteria


    【解决方案1】:

    您的代码中有多个错误。

    首先:你选择了错误的重载。

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

    代替:

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

    这是因为您使用了无类型的 CriteriaBuilder。解决方法是将第一个参数作为Path&lt;Long&gt; 传递,而不是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=?"
    

    【讨论】:

      猜你喜欢
      • 2019-08-26
      • 2015-12-13
      • 2014-04-06
      • 2020-02-23
      • 2022-11-10
      • 2013-02-20
      • 2020-06-22
      • 2019-09-03
      • 2019-10-22
      相关资源
      最近更新 更多