代码之家  ›  专栏  ›  技术社区  ›  Иван Гладуш

IllegalArgumentException:参数值函数。AggregationFunction与预期的类型[java.lang.Long(不适用)]不匹配

  •  0
  • Иван Гладуш  · 技术社区  · 6 年前

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

        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(不适用)]不匹配

    如何解决我的问题?

    1 回复  |  直到 6 年前
        1
  •  2
  •   Lesiak    6 年前

    您的代码中有多个错误。

    第一:您选择了错误的重载。

    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=?"