【问题标题】:JpaRepository: using repositories in @PostPersistJpaRepository:在@PostPersist 中使用存储库
【发布时间】:2015-04-14 09:15:23
【问题描述】:

我有两个实体

class A {
    ...
    Integer totalSum;
    Set<B> b;
}

class B {
    ...
    Integer value;
    A container;
}

我希望 a.totalSum 是每个 a.b.value 的总和;

也许最好的解决方案是在 db 中查看,但我想听 BRepository 中的更改并更新 A 记录。

我愿意:

@PostPersist
@PostUpdate
@PostRemove
private void recalculateSums(B b) {
    AutowireHelper.autowire(this, this.aRepository);
    AutowireHelper.autowire(this, this.bRepository);
    A a =   b.getContainer();
    a.setTotalSum(bRepository.sumByA(s));
    aRepository.save(s);
}

在 BRepository 中:

@Query("select sum(b.value) from B b where b.container = :a")
Long sumByA(@Param("a") A a);

我有错误:org.springframework.dao.DataIntegrityViolationException: could not execute statement; SQL [n/a]; constraint ["PRIMARY KEY ON PUBLIC.B(ID)"; SQL statement: insert into b (VALUE, CONTAINER_ID, ID) values (?, ?, ?)

我做错了什么?

如果我这样做

    a.setTotalSum(a.getTotalSum()+1);
    aRepository.save(s);

一切正常,但如果我这样做了

    a.setTotalSum(a.getTotalSum()+1);
    aRepository.saveAndFlush(s);

我有同样的错误。

【问题讨论】:

    标签: spring hibernate jpa spring-data h2


    【解决方案1】:

    我明白您为什么要这样做,但我认为这会产生大量关于数据完整性的潜在问题。

    如果您希望 B 的总和可用于 A 而不必加载和迭代所有 B,那么您可以实施其他三个选项,所有这些选项都比您的提议更强大。

    1. 如您所述,创建一个视图。然后,您可以将一个实体(例如 SummaryData)映射到此视图,并将 A 的一对一映射到 SummaryData,以便您可以执行 a.getSummaryData().getTotalSum();

    2. 或者,您可以使用 Hibernate 特定的 @Formula 注释,该注释将在加载实体时发出内联选择。

      @Formula("(select sum(value) from B b inner join A a where b.a_id= a.id and a.id =id 私有整数总和;

    3. 最后,根据您的数据库的功能,您可以创建一个虚拟列并映射一个属性,就像对任何其他字段一样。

    1 和 3 显然需要更改架构,但您的应用程序将保持 JPA 兼容。 2 不需要任何架构更改,但如果这很重要,则会违反严格的 JPA 合规性。

    【讨论】:

    • 谢谢。 @Formula 帮助我。但是我仍然不明白如何正确使用我的方法。
    • @Formula 对我来说有一个严重的缺陷——我想通过这个专栏建立索引。我不能用@Formula 做到这一点。我可以在数据库上使用触发器来完成它,但是如果我想创建独立于数据库应用程序,我认为最好使用休眠拦截器..
    猜你喜欢
    • 1970-01-01
    • 2020-06-06
    • 2015-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-09
    • 2021-02-02
    相关资源
    最近更新 更多