【问题标题】:Projection in Hibernate/JPA in Spring Boot to pull data from multiple OneToMany and manyToOne relationshipsSpring Boot 中的 Hibernate/JPA 中的投影以从多个 OneToMany 和 manyToOne 关系中提取数据
【发布时间】:2023-04-09 03:22:02
【问题描述】:

我需要创建一个 JPA 投影,它将从 Entity1 中提取所有记录并包含来自 Entity4 的记录计数。

以下是映射的四个实体及其关系:

Entity1 (ManyToOne) Entity2 (OneToMany) Entity3 (OneToMany) Entity4

在 SQL 中,这可以通过简单的内联选择语句轻松解决。在 JPA 投影中,我正在尝试执行以下操作。

@Value("#{target.getEntity2().getEntity3().getEntity4().size()}")
String  getEntity4Count();  

在上面的这段代码中,投影在 Entity1 上。当我添加 Entity4 时它会引发异常。下面的代码有效。

@Value("#{target.getEntity2().getEntity3().size()}")
String  getEntity3Count();

这甚至是提取这些数据的正确方法吗?所有示例似乎都指向两个实体之间的关系,这对于非常简单的应用程序非常有用,但业务应用程序中的 SQL 往往非常复杂。

有没有办法用JPQL等其他方法完成上述操作?处理需要针对一组实体执行的大量复杂 SQL 的最佳方法是什么?

【问题讨论】:

    标签: java spring-boot hibernate jpa


    【解决方案1】:

    Spring Data Projections 并不是真正为这种映射而设计的,因为它会获取实体并在@Value 注释中作为 SPEL(Spring 表达式语言)代码执行您的“映射”。我想您更愿意使用更高效的 SQL?

    这是Blaze-Persistence Entity Views 的完美用例。

    我创建了该库以允许在 JPA 模型和自定义接口或抽象类定义模型之间轻松映射,例如 Spring Data Projections on steroids。这个想法是您按照自己喜欢的方式定义目标结构(域模型),并通过 JPQL 表达式将属性(getter)映射到实体模型。

    使用 Blaze-Persistence Entity-Views 的用例的 DTO 模型可能如下所示:

    @EntityView(Entity1.class)
    public interface Entity1Dto {
        @IdMapping
        Long getId();
        @Mapping("COUNT(entity2.entity3.entity4)")
        Long getCount();
    }
    

    查询是将实体视图应用于查询的问题,最简单的就是通过 id 进行查询。

    Entity1Dto a = entityViewManager.find(entityManager, Entity1Dto.class, id);

    Spring Data 集成让您可以像使用 Spring Data Projections 一样使用它:https://persistence.blazebit.com/documentation/entity-view/manual/en_US/index.html#spring-data-features

    【讨论】:

      猜你喜欢
      • 2021-06-15
      • 2013-06-17
      • 1970-01-01
      • 2016-03-08
      • 2017-03-08
      • 1970-01-01
      • 2023-04-09
      • 2019-02-24
      • 1970-01-01
      相关资源
      最近更新 更多