JPA使用Spring Data Specification进行删除和更新

JPA使用Spring Data Specification进行删除和更新

问题描述:

JPA规范功能强大,可以构建WHERE子句.但是,它似乎只为SELECT定义(使用findAll方法).

JPA Specification is powerful in order to build WHERE clauses. But, it seems to be defined only for SELECT (with findAll method).

使用DELETE和UPDATE是否可能具有相同的行为?因此,有可能避免在删除或更新范围之前选择范围.

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

您可以使用CriteriaUpdate和CriteriaDelete.我在这里通过RSQL查询建立我的规范,但也可以通过许多其他方式来完成(请参见

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