【问题标题】:Avoid unncessary relationship Rest Api Response JPA避免不必要的关系 Rest Api Response JPA
【发布时间】:2022-11-30 12:55:46
【问题描述】:
我的数据库中有一个包含 10 个表的 springboot 应用程序。当我在一个表上发出获取请求时,它会在所有 10 个表中都有任何相关记录的所有表中返回一个响应。我用的是Lazy fetch,问题并没有解决。我只需要返回前端应用程序预期的响应。例如,如果客户端只需要学生,那么 REST API 应该只返回学生(而不是它的子实体)。我怎么解决这个问题。
【问题讨论】:
标签:
java
spring-boot
hibernate
jpa
spring-data-jpa
【解决方案1】:
您可以解析 JSON 响应并通过自定义从 Response 中获取一个或多个特定字段。
另一种选择是在您不希望它们成为响应一部分的字段上使用 @JsonIgnore 注释。
【解决方案2】:
您可以通过为您的用例创建 DTO 来解决这个问题,我认为这是 Blaze-Persistence Entity Views 的完美用例。
我创建了库以允许在 JPA 模型和自定义接口或抽象类定义的模型之间轻松映射,类似于 Spring Data Projections on steroids。这个想法是您按照自己喜欢的方式定义目标结构(领域模型),并通过 JPQL 表达式将属性(getter)映射到实体模型。
使用 Blaze-Persistence Entity-Views,您用例的 DTO 模型可能如下所示:
@EntityView(Student.class)
public interface StudentDto {
@IdMapping
Long getId();
String getName();
Set<CourseDto> getCourses();
@EntityView(Course.class)
interface CourseDto {
@IdMapping
Long getId();
String getName();
}
}
查询是将实体视图应用于查询的问题,最简单的就是通过 id 进行查询。
StudentDto a = entityViewManager.find(entityManager, StudentDto.class, id);
Spring Data 集成允许您几乎像使用 Spring Data Projections 一样使用它:https://persistence.blazebit.com/documentation/entity-view/manual/en_US/index.html#spring-data-features
Page<StudentDto> findAll(Pageable pageable);
最好的部分是,它只会获取实际需要的状态!