问题描述
我正在使用Spring Boot 2.3.0,Hibernate 5和MysqL 8.0 我正在尝试在我的JQPL查询中使用联接获取来初始化ManyToOne关系,但由于该实体未加载,因此无法正常工作。
在实体中,我有:
@Entity
public class Academic_Record {
@JoinColumn(name = "product_id",nullable = false)
@ManyToOne(fetch = FetchType.LAZY,optional = false)
private Product product;
.....
在存储库中:
@Query(value = "select ar from Academic_Record ar " +
"join fetch ar.product p " +
"where ar.enrollmentStudent.id = :enrollmentStudentId " +
"and ar.product.id = :productId")
Academic_Record findByEnrollmentStudentIdAndProductIdWithProduct(Long enrollmentStudentId,Integer productId);
但是如果尝试:
Academic_Record academicRecord = academicRecordDao.findByEnrollmentStudentIdAndProductIdWithProduct(1,2);
当我在调试模式下观看AcademicRecord的产品属性时,我只会看到一个代理对象,而没有加载该产品。
怎么了?
非常感谢
解决方法
这是FetchType.LAZY
的默认行为,当您尝试获取产品时,代理将被解析。如果要同时加载产品,请改用FetchType.EAGER
。
@JoinColumn(name = "product_id",nullable = false)
@ManyToOne(fetch = FetchType.EAGER,optional = false)
private Product product;