[英]LazyInitializationException using hibernate enhancement with @Basic(fetch = FetchType.LAZY)
I have this persistent entity with a lob field that gets eagerly fetched so I configured the hibernate-enhance-maven-plugin and made it lazy:我有一个带有 lob 字段的持久实体,它被急切地获取,所以我配置了hibernate-enhance-maven-plugin并使它变得懒惰:
@Lob
@Column(name = "MY_FIELD")
@Basic(fetch = FetchType.LAZY)
private byte[] lazyField;
Now I am getting LazyInitializationException at a fairly simple test:现在我在一个相当简单的测试中得到了LazyInitializationException :
myJpaRepo.findAll().get(0).getLazyField()
Unable to perform requested lazy initialization [MyEntity.lazyField] - no session and settings disallow loading outside the Session
无法执行请求的延迟初始化 [MyEntity.lazyField] - 没有 session 并且设置不允许在 Session 之外加载
I use Spring Boot and have not done anything specific to configure hibernate.我使用 Spring 引导并且没有做任何特定的配置 hibernate。 This test uses a h2 database.
此测试使用 h2 数据库。
MyRepo is annotated with @Transactional. MyRepo 使用@Transactional 进行注释。
If I also annotate the executing method, there is no Exception thrown:如果我还注释执行方法,则不会抛出异常:
@Transactional
public void test(){
myJpaRepo.findAll().get(0).getLazyField()
}
Will I need to annotate as transactional every single time someone tries to fetch the lazy field, or is there something else I can do to avoid that?每次有人尝试获取惰性字段时,我是否需要将其注释为事务性的,还是我可以采取其他措施来避免这种情况?
Error says that you are trying to access association outside of hibernate session/transaction boundary.错误表示您正在尝试访问 hibernate 会话/事务边界之外的关联。
In this case you will have to annotate test method with @transaction as well so that you are well within transaction boundary and have active hibernate session.在这种情况下,您还必须使用 @transaction 注释测试方法,以便您处于事务边界内并具有活动的 hibernate session。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.