本文介绍了@Transactional 方法中的 LazyInitializationException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在执行以下操作时尝试访问延迟加载的异常时遇到 org.hibernate.LazyInitializationException 错误:

I am running into the org.hibernate.LazyInitializationException error when I try to access a lazy loaded exception when excecuting the following:

@Transactional
public void displayAddresses()
{
     Person person = getPersonByID(1234);
     List<Address> addresses = person.getAddresses(); // Exception Thrown Here

     for(Address address : addresses)
          System.out.println(address.getFullAddress());
}

我的实体如下所示:

@Entity
@Table("PERSON_TBL")
public class Person
{
     ...

     @OneToMany(cascade=CascadeType.ALL, targetEntity=Address.class, mappedBy="person")
     private List<Address> addresses;

     ...
}

@Entity
@Table("ADDRESS_TBL")
public class Address
{
     ...

     @ManyToOne(targetEntity=Person.class)
     @JoinColumn(name="PERSON_ID", referencedColumnName="PERSON_ID")
     Person person;

     ...
}

我的印象是,通过在我的 displayAddresses() 方法中使用 @Transactional 注释,它会使会话保持活动状态,直到方法完成,允许我访问延迟加载的地址收藏.

I was under the impression that by using the @Transactional annotation in my displayAddresses() method, it would keep the session alive until the method was completed, allowing me to access the lazy-loaded Address collection.

我错过了什么吗?

编辑

根据 Tomasz 的建议:在我的 displayAddresses() 方法中,TransactionSynchronizationManager.isActualTransactionActive(), 的状态变成了 false.

In accordance with Tomasz's advice: Within my displayAddresses() method, the status of TransactionSynchronizationManager.isActualTransactionActive(), turned out to be false.

这确实缩小了问题的范围,但为什么此时我的交易不活跃?

That does narrow down the problem, but why would my Transaction not be active at this point?

推荐答案

在我的配置文件中有 <tx:annotation-driven/> 并使用我的服务类的 Spring 管理版本(调用 displayAddresses() 方法)成功了.

Having <tx:annotation-driven /> in my configuration file and using a Spring-managed version of my service class (to call the displayAddresses() method) did the trick.

这篇关于@Transactional 方法中的 LazyInitializationException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 07:00
查看更多