[jboss-user] [EJB 3.0] - Re: LazyInitializationException in many-to-many relation tha
jaikiran
do-not-reply at jboss.com
Tue Apr 22 10:56:04 EDT 2008
anonymous wrote : I am getting a LazyInitializationException: failed to lazily initialize a collection of role : eco.ejb3.entity.Subject.usersThatSubscribedToMe, no session or session was closed
A LazyInitializationException occurs when the entity or its associated collection is being accessed when the session is no longer available. In your case, i guess, your JUnit test first called a method on the bean to retrieve the entity. When this is done, a session is opened to retrieve that persistent object. The object is then returned to the client (your JUnit test case). At the same time the session is closed (since the bean method transaction completed).
Now at some later point in time, in your testcase you invoke the addPublicSubject method on the bean passing it the entity which was loaded as part of a session which no longer exists. Now when you try to access the entities collection, it throws this LazyInitializationException.
To avoid this exception, you either have to access that collection when the session is open or use the merge method on the entitymanager to attach the entity to a session. Like this:
@TransactionAttribute(TransactionAttributeType.REQUIRED)
| public void addPublicSubject(Subject s, User u) {
|
| //merge the subject. Remember that the merge operation, returns a merged object.
| // So use this returned object, henceforth in the code.
| Subject mergedSubject = entityManager.merge(s);
|
| //Let's also merge the User since it too was detached
| User mergedUser = entityManager.merge(u);
|
| mergedSubject.getUsersThatSubscribedToMe().add(mergedUser);
|
| entityManager.persist(mergedSubject);
|
| }
This is just a pseudo-code and you might have to do some additional changes to get this working. If this doesn't work, then please post back with the exception logs and the code changes that you did.
While posting the logs or code or xml content, remember to wrap it in a code block using the Code button in the message editor window and please hit the Preview button to make sure your post is correctly formatted
View the original post : http://www.jboss.com/index.html?module=bb&op=viewtopic&p=4145885#4145885
Reply to the post : http://www.jboss.com/index.html?module=bb&op=posting&mode=reply&p=4145885
More information about the jboss-user
mailing list