LazyInitializationException在@Transactional方法中 [英] LazyInitializationException Within a @Transactional Method
问题描述
在执行下列操作时,当我尝试访问延迟加载的异常时,我遇到 org.hibernate.LazyInitializationException
错误:
@Transactional
public void displayAddresses()
{
Person person = getPersonByID(1234);
列表<地址> addresses = person.getAddresses(); //在此处抛出异常
(地址地址)
System.out.println(address.getFullAddress());
}
我的实体看起来像这样:
@Entity
@Table(PERSON_TBL)
public class Person
{
...
@OneToMany(cascade = CascadeType.ALL,targetEntity = Address.class,mappedBy =person)
private List< Address>地址;
}
@Entity
@Table(ADDRESS_TBL)
公共类地址
{
...
@ManyToOne(targetEntity = Person.class)
@JoinColumn(name =PERSON_ID,referencedColumnName =PERSON_ID)
Person person;
...
}
通过在我的 displayAddresses()
方法中使用@Transactional注释,它将使会话保持活动状态,直到方法完成,允许我访问延迟加载的Address集合。
我缺少什么吗?
编辑
根据Tomasz的建议:在我的 displayAddresses()
方法中, TransactionSynchronizationManager.isActualTransactionActive(),
原来是 false
。
这确实缩小了问题的范围,但为什么我的交易在此时不会处于活动状态?
< tx:annotation-driven />
,并使用服务类的Spring管理版本调用displayAddresses()方法)做了诀窍。 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());
}
My entities look like this:
@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;
...
}
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.
Am I missing something?
EDIT
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?
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.
这篇关于LazyInitializationException在@Transactional方法中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!