JPA规范功能强大,可以构建WHERE子句。但是,似乎只为SELECT(使用findAll方法)定义。
是否可以使用DELETE和UPDATE具有相同的行为?因此,在删除或更新范围之前,可以避免选择范围。
THX
答案 0 :(得分:0)
您可以使用CriteriaUpdate和CriteriaDelete。我在这里从RSQL查询构建我的规范,但也可以通过许多其他方式完成(参见https://www.programcreek.com/java-api-examples/index.php?api=javax.persistence.criteria.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();