【发布时间】:2021-03-04 16:52:38
【问题描述】:
我在一个实体说类与学生之间有一个@OneToMany 关系。现在每个班级至少可以有 100 名学生。这就是我与 Student 的关系在 Class 实体中的定义方式
@OneToMany(mappedBy = "classDataEntity", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
private List<StudentDataEntity> studentDataEntities;
我们使用两种方法来检查通过 ID (PK) 获取类的性能
- 可选的 findById(ID id); // with fetchType Eager with Students
- 在存储库中创建一个新方法,使用 @Query 连接 classId 中的两个表
我们从同一个服务类方法调用这两个方法,例如
@Transactional
public ClassDataEntity fetchClassEntity(Long classId){
ClassDataEntity classDataEntityJOined = repo.fetchClassWithStudents(id);
ClassDataEntity classDataEntity = repo.findById(id);
}
我的理解是对很多学生来说,加入应该表现得更好,因为它对 DB 的调用更少,因此网络调用更少。但在上述情况下,我们看到 findById 的表现要好得多
是不是因为 id 的数据已经在 session 中了?当通过 Crud Repositories 调用时,何时创建和销毁 Hibernate 会话
【问题讨论】:
-
你能打开 sql 日志来查看每个选项的 man 查询是如何运行的吗?会话应该与每个事务一起创建。
标签: spring hibernate spring-data-jpa spring-data