我正在尝试使用休眠条件构建器执行下一个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模式。还是同样的问题。
我想念什么?
答案 0 :(得分:1)
您必须指定path属性引用Long:
update.set((Path<?>) root.<Long>get("balance"), cb.sum(root.<Long>get("balance"), amount));