Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
836 views
in Technique[技术] by (71.8m points)

hibernate - LazyInitializationException Within a @Transactional Method

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This is already answered, but just wanted to post an alternative answer which worked for me in a similar case - for future generations ;)

In my case the issue was caused by the fact that the instance which contained the lazy-loaded collection had been manually evicted (all within transaction boundaries).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...