How to Get the Session Object If I Have the Entity-Manager

How can I get the session object if I have the entity-manager?

To be totally exhaustive, things are different if you're using a JPA 1.0 or a JPA 2.0 implementation.

JPA 1.0

With JPA 1.0, you'd have to use EntityManager#getDelegate(). But keep in mind that the result of this method is implementation specific i.e. non portable from application server using Hibernate to the other. For example with JBoss you would do:

org.hibernate.Session session = (Session) manager.getDelegate();

But with GlassFish, you'd have to do:

org.hibernate.Session session = ((org.hibernate.ejb.EntityManagerImpl) em.getDelegate()).getSession(); 

I agree, that's horrible, and the spec is to blame here (not clear enough).

JPA 2.0

With JPA 2.0, there is a new (and much better) EntityManager#unwrap(Class<T>) method that is to be preferred over EntityManager#getDelegate() for new applications.

So with Hibernate as JPA 2.0 implementation (see 3.15. Native Hibernate API), you would do:

Session session = entityManager.unwrap(Session.class);

getting session object from EntityManager in petclinic jpa

The reason the code is organized like this in the sample project is because all persistence code would be better suited in the petclinic.model package which contains the project's DAOs (data access objects) the classes with the xxxRepository naming convention. The job of the controller is to simply route HTTP requests to business logic and should be kept slim (logic-wise). For your example you might be better off creating a new DAO and service class, maybe called FileService and FileRepository, along with their corresponding implementations (you can use existing classes in the sample for examples). Once these classes are created you could include the FileService in any controllers that needed it. For the PetController the flow of your logic would look something like this PetController -> FileService -> FileRepository.saveFile(). If you wanted to centralize the entity manager I would only suggest doing it for a generic DAO class that the other DAOs descend from and not including the entity manager in the controllers.

Accessing Hibernate Session from EJB using EntityManager

Bozho and partenon are correct, but:

In JPA 2, the preferred mechanism is entityManager.unwrap(class)

HibernateEntityManager hem = em.unwrap(HibernateEntityManager.class);
Session session = hem.getSession();

I think your exception is caused because you are trying to cast to an implementation class (perhaps you were dealing with a JDK proxy). Cast to an interface, and everything should be fine (in the JPA 2 version, no casting is needed).

Get Hibernate SessionFactory from JPA's entityManagerFactory

I solved it by injecting it, defining the bean like this http://docs.spring.io/spring/docs/3.0.x/spring-framework-reference/html/orm.html#orm-session-factory-setup



Related Topics



Leave a reply



Submit