Grails and Hibernate's Lazy Initialization Exception
Asked Answered
B

2

10

Where are the most common places where you've gotten an org.hibernate.LazyInitializationException in Grails, what was the cause and how did you solve it ?

I think this one exception comes up a lot for novice, so if you'd provide more examples, it would be great.

Blackmarketeer answered 2/9, 2009 at 14:24 Comment(0)
A
10

Lets take an example :

class Book {
  String title
  Author author
}

class Author {
  ...
}

Book book = Book.get(1)

As we know, default fetch mode is lazy in domain classes. Considering the above example, say we get the book object, then Book object gets attached to the hibernate session object i.e first level cache automatically. And after the domain object gets detached from the session object and then we try to fetch book.author, at this moment it raises the Lazy initialization exception.

So the solution is, to have either fetch mode as eager or attach your book object to hibernate session using the code given below :

if(!book.isAttached()){
     book.attach()
}

The description given above is one of the scenario. There could be many more. I request others to please share.

Aconite answered 8/9, 2009 at 4:42 Comment(3)
That works for me really good, but it's tedious to place it everywhere it's needed!Financial
@Financial Amit doesn't seem active in SO. Do you know what causes and object to be detached in one session?Trajectory
@AlexanderSuraphel I really don't know. I just place it when exception rises somewhereFinancial
P
1

I was getting this error because I was checking if a user had permission to do some action with JSecurity/Shiro in a service that was not transactional. In the end I just had to set the service as transactional to get rid of the exception.

More info here.

Plight answered 2/9, 2009 at 15:35 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.