-->
These old forums are deprecated now and set to read-only. We are waiting for you on our new forums!
More modern, Discourse-based and with GitHub/Google/Twitter authentication built-in.

All times are UTC - 5 hours [ DST ]



Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 2 posts ] 
Author Message
 Post subject: How to get entityManager by using an entity class
PostPosted: Tue Apr 09, 2013 7:11 am 
Newbie

Joined: Tue Jan 29, 2013 5:33 am
Posts: 4
How to reach the entity manager which managed the entity. I mean; suppose that i have an entity reference in the sessionBean, how can i get entityManager of this entity belonged one?
Thx
bgrds


Top
 Profile  
 
 Post subject: Re: How to get entityManager by using an entity class
PostPosted: Thu Apr 11, 2013 4:08 am 
Expert
Expert

Joined: Tue Jun 16, 2009 3:36 am
Posts: 990
Entity objects don't have a reference to the session (entityManager) which loaded/created them.
An exception are persistent collections, they have such a reference in order to allow lazy loading.
So if your entity object has persistent collections, you can get the original session by following hack:

Code:
AbstractPersistentCollection collection = (AbstractPersistentCollection ) myentity.getAllChilds();
Session = getSession();


Once you have the session you should be able to map it to the right entityManager.
But anyway this is a hack which I do not recommend.

I prefer another approach, which work also on entities without having any collections inside:
I use a PostLoadListener to memoryze the session (entityManager) like this:

Code:
<property name="hibernate.ejb.event.post-load" value="MyPostLoadListener"/>



Code:
public class MyPostLoadListener extends DefaultPostLoadEventListener {
   
   @Override
   public void onPostLoad(PostLoadEvent event) {
      super.onPostLoad(event);

      if (event.getEntity() != null) {
         SessionImpl session = (SessionImpl) event.getSession();
         MyPersistentMappedSuperclass= (MyPersistentMappedSuperclass) event.getEntity();
         myentity.setSession(session); // holding the session reference in a transient field
      }
      else throw new HibernateException("Failed postload event! (getEntity() == null)");
   }

}


Top
 Profile  
 
Display posts from previous:  Sort by  
Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 2 posts ] 

All times are UTC - 5 hours [ DST ]


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum

Search for:
© Copyright 2014, Red Hat Inc. All rights reserved. JBoss and Hibernate are registered trademarks and servicemarks of Red Hat, Inc.