更新查询期间条件构建器错误:BinaryArithmeticOperation与预期类型不匹配

时间:2019-01-24 14:36:45

标签: java hibernate jpa spring-data-jpa criteria-api

我正在尝试使用休眠条件构建器执行下一个SQL:

update account set balance = balance + 500;

这是我的查询构建代码:

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

update.set("balance", cb.sum(root.get("balance"), amount));

getEntityManager().createQuery(update).executeUpdate();

我也尝试过:

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

ParameterExpression<Long> amountExpression = cb.parameter(Long.class);

update.set("balance", cb.sum(root.get("balance"), amountExpression));

getEntityManager().createQuery(update)
    .setParameter(amountExpression, amount).executeUpdate();

两次执行都会产生下一个错误:

org.springframework.dao.InvalidDataAccessApiUsageException: Parameter value [org.hibernate.query.criteria.internal.expression.BinaryArithmeticOperation@53e0be2d] did not match expected type [java.lang.Long (n/a)]; nested exception is java.lang.IllegalArgumentException: Parameter value [org.hibernate.query.criteria.internal.expression.BinaryArithmeticOperation@53e0be2d] did not match expected type [java.lang.Long (n/a)]] with root cause
"java.lang.IllegalArgumentException: Parameter value [org.hibernate.query.criteria.internal.expression.BinaryArithmeticOperation@53e0be2d] did not match expected type [java.lang.Long (n/a)]

MySQL数据库中的余额类型为:balance bigint UNSIGNED
代码中的amount变量的类型为Long
balance的{​​{1}}属性是JBCAccount

我还尝试使用Long(即不使用balance bigint)重新创建MySQL模式。还是同样的问题。

我想念什么?

1 个答案:

答案 0 :(得分:1)

您必须指定path属性引用Long:

update.set((Path<?>) root.<Long>get("balance"), cb.sum(root.<Long>get("balance"), amount));