问题
JPA Specification is powerful in order to build WHERE clauses. But, it seems to be defined only for SELECT (with findAll method).
Is it possible to have the same behavior with DELETE and UPDATE? So that, it would be possible to avoid selecting scope before deleting or updating it.
Thx
回答1:
You can use CriteriaUpdate and CriteriaDelete. Im building my specification from a RSQL query here but it can be done in a lot of other ways as well (see 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();
来源:https://stackoverflow.com/questions/40883348/jpa-use-spring-data-specification-for-delete-and-update