Oli*_*ien 5 java spring jpa spring-data-jpa
JPA 规范对于构建 WHERE 子句非常强大。但是,它似乎只为 SELECT 定义(使用 findAll 方法)。
DELETE 和 UPDATE 是否可以有相同的行为?这样,就可以避免在删除或更新范围之前选择范围。
谢谢
您可以使用 CriteriaUpdate 和 CriteriaDelete。我在这里从 RSQL 查询构建我的规范,但也可以通过许多其他方式完成(请参阅https://www.programcreek.com/java-api-examples/index.php?api=javax.persistence。标准.CriteriaUpdate)。
Node rootNode = new RSQLParser(CustomRsqlOperators.getOperators()).parse(filter);
Specification<Voucher> spec = rootNode.accept(new CustomRsqlVisitor<Voucher>());
CriteriaBuilder builder = entityManager.getCriteriaBuilder();
CriteriaUpdate<Voucher> update = builder.createCriteriaUpdate(Voucher.class);
Root<Voucher> root = update.from(Voucher.class);
Predicate condition = spec.toPredicate(root, builder.createQuery(), builder);
update.where(condition);
if (voucherUpdate.getIsUsed() != null) {
update.set("isUsed", voucherUpdate.getIsUsed());
}
Query q = entityManager.createQuery(update);
int updated = q.executeUpdate();
entityManager.flush();
Run Code Online (Sandbox Code Playgroud)