我想使用@EntityGraph
在我的实体中加载惰性字段。
我有一个简单的实体:
@Data
@Entity
@Table(name = "users")
@EqualsAndHashCode(of = "name")
@ToString(exclude = {"bigField", "role"})
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private int id;
@Column(name = "name", length = 100)
private String name;
@Basic(fetch = FetchType.LAZY)
@Column(name = "big_field")
private String bigField;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "role_id")
private Role role;
}
和存储库:
public interface UserRepository extends JpaRepository<User, Integer> {
@EntityGraph(attributePaths = {"role", "bigField"})
User findById(Integer id);
}
当我尝试使用findById
方法吸引用户时:
final User user = userRepository.findById(1);
log.info("USER = {}", user);
log.info("ROLE = {}", user.getRole());
log.info("BIG FIELD = {}", user.getBigField());
休眠生成下一个查询:
Hibernate:
select
user0_.id as id1_1_0_,
role1_.id as id1_0_1_,
user0_.name as name3_1_0_,
user0_.role_id as role_id4_1_0_,
role1_.name as name2_0_1_
from
users user0_
left outer join
role role1_
on user0_.role_id=role1_.id
where
user0_.id=?
如您所见,它会加载role
字段,但不会加载bigField
。当我尝试获取bigField
属性时,会引发异常:
Caused by: org.hibernate.LazyInitializationException: Unable to perform requested lazy initialization [com.example.demo.entity.User.bigField] - no session and settings disallow loading outside the Session
at org.hibernate.bytecode.enhance.spi.interceptor.Helper.throwLazyInitializationException(Helper.java:164) ~[hibernate-core-5.3.3.Final.jar:5.3.3.Final]
at org.hibernate.bytecode.enhance.spi.interceptor.Helper.performWork(Helper.java:59) ~[hibernate-core-5.3.3.Final.jar:5.3.3.Final]
at org.hibernate.bytecode.enhance.spi.interceptor.LazyAttributeLoadingInterceptor.loadAttribute(LazyAttributeLoadingInterceptor.java:76) ~[hibernate-core-5.3.3.Final.jar:5.3.3.Final]
at org.hibernate.bytecode.enhance.spi.interceptor.LazyAttributeLoadingInterceptor.fetchAttribute(LazyAttributeLoadingInterceptor.java:72) ~[hibernate-core-5.3.3.Final.jar:5.3.3.Final]
at org.hibernate.bytecode.enhance.spi.interceptor.LazyAttributeLoadingInterceptor.intercept(LazyAttributeLoadingInterceptor.java:61) ~[hibernate-core-5.3.3.Final.jar:5.3.3.Final]
at org.hibernate.bytecode.enhance.spi.interceptor.LazyAttributeLoadingInterceptor.readObject(LazyAttributeLoadingInterceptor.java:296) ~[hibernate-core-5.3.3.Final.jar:5.3.3.Final]
at com.example.demo.entity.User.$$_hibernate_read_bigField(User.java) ~[main/:na]
我正在使用Spring Boot v1.5.14.RELEASE和hibernate v5.3.3.Final。
在gradle.build中,我有下一个配置:
hibernate {
enhance {
enableLazyInitialization = true
enableDirtyTracking = true
enableAssociationManagement = true
enableExtendedEnhancement = false
}
}
有人知道这个问题的根源吗,我该如何创建解决方法?