Search code examples
javapostgresqlhibernatehibernate-criteria

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


I want to increment my variable via criteria builder. I wrote the following code

    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();

MyEntity:

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

Database table has the following structure:

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

But I've got the following error

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)]

How can I resolve my problem?


Solution

  • There are multiple errors in your code.

    First: you select the wrong overload.

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

    instead of:

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

    This is because you use untyped CriteriaBuilder. The way to solve it is to pass the first argument as a Path<Long>, not String.

    Second: I'm not sure what your query is trying to accomplish, but it looks there is one sum to many. I believe it should look like:

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

    Which will generate:

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