OlivierTerrien
OlivierTerrien

Reputation: 2601

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

Upvotes: 6

Views: 8160

Answers (1)

dirkaholic
dirkaholic

Reputation: 350

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

Upvotes: 5

Related Questions