我使用的是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;