[英]How to perform update operation using CriteriaUpdate in sping Data JPA?
As spring data JPA provide specification to get result like below由于弹簧数据 JPA 提供规范以获得如下结果
public static Specification<Customer> customerHasBirthday() {
return new Specification<Customer> {
public Predicate toPredicate(Root<T> root, CriteriaQuery query, CriteriaBuilder cb) {
return cb.equal(root.get(Customer_.birthday), today);
}
};
}
and then we can pass above specification in repository method customerRepository.findAll(customerHasBirthday);
然后我们可以在存储库方法
customerRepository.findAll(customerHasBirthday);
传递上述规范customerRepository.findAll(customerHasBirthday);
Now I want to perform update operation using criteria update in spring data JPA like below现在我想在 spring 数据 JPA 中使用标准更新来执行更新操作,如下所示
public static Specification<Customer> upadteCustomerName() {
return new Specification<Customer> {
public Predicate toPredicate(Root<Customer> root, CriteriaQuery query, CriteriaBuilder cb) {
CriteriaUpdate<Customer> update = cb.createCriteriaUpdate(Customer.class)
update.set("name", "newName");
return update.where(cb.greaterThanOrEqualTo(root.get("id"), 2));
}
};
}
Obviously I will get compile time error as显然我会得到编译时错误
CriteriaUpdate can not be converted into predicate
CriteriaUpdate 不能转换为谓词
Is spring data JPA provide any easy way to implement CriteriaUpdate and then directly pass the instance to Repository method like in Get operation we have findAll()
method? Spring Data JPA 是否提供了任何简单的方法来实现 CriteriaUpdate 然后直接将实例传递给 Repository 方法,就像在 Get 操作中我们有
findAll()
方法一样?
or is there any other best way to implement criteriaUpdate in spring Data JPA?或者有没有其他最好的方法在 spring Data JPA 中实现标准更新?
Based on this answer you can do like this:基于这个答案,你可以这样做:
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaUpdate<Customer> q = cb.createCriteriaUpdate(Customer.class);
Root<Customer> root = q.from(Customer.class);
q.set(root.get("name"), "newName")
.where(cb.greaterThanOrEqualTo(root.get("id"), 2));
int result = em.createQuery(q).executeUpdate();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.