JPA use Spring Data Specification for delete and update

社会主义新天地 提交于 2021-02-09 11:33:34

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!