简体   繁体   中英

JPA use Spring Data Specification for delete and update

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

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM