【问题标题】:JPA use Spring Data Specification for delete and updateJPA 使用 Spring Data Specification 进行删除和更新
【发布时间】:2016-11-30 08:17:27
【问题描述】:

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

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

谢谢

【问题讨论】:

  • 你找到解决办法了吗?
  • 没有。我必须使用“查找”然后“删除”或“保存”方法

标签: java spring jpa spring-data-jpa


【解决方案1】:

您可以使用 CriteriaUpdate 和 CriteriaDelete。我在这里从 RSQL 查询构建我的规范,但也可以通过许多其他方式完成(参见 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();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-05-25
    • 1970-01-01
    • 2021-12-19
    • 1970-01-01
    • 2016-12-07
    • 1970-01-01
    • 2023-03-29
    • 1970-01-01
    相关资源
    最近更新 更多