How can I get an EntityManager from an org.hibernate.Session

0

Working with hibernate using Session.

public class HibernateUtil {

    private static final SessionFactory sessionFactory = buildSessionFactory();

    // A SessionFactory is set up once for an application
    private static SessionFactory buildSessionFactory() {
        try {
            return new Configuration().configure("hibernate.cfg.xml").buildSessionFactory();
        } catch (Throwable e) {
            System.out.println("Criação inicial do objeto SessionFactory falhou. Erro: " + e);
            throw new ExceptionInInitializerError(e);
        }
    }

    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }
}

Using the session factory as default

public static ProdutoDAO criarProdutoDAO() {
        ProdutoDAOImpl produtoDAOImpl = new ProdutoDAOImpl();
        produtoDAOImpl.setSession(HibernateUtil.getSessionFactory().getCurrentSession());
        return produtoDAOImpl;
} 

So creating my session for my DAOs ...

public class PedidoDAOImpl implements PedidoDAO {

    private Session session;

    public Session getSession() {
        return session;
    }

    public void setSession(Session session) {
        this.session = session;
    }
    ...
}

But within DAO I had the need to use an EntityManager to create a custom query where I get an unmapped object list in hibernate ...

Getting a Session from an EntityManager I've already found.

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

But getting an EntityManager from a Session is not yet.

I would like to know if it is possible to transform, retrieve or even create an EntityManager from a Session.

Thank you in advance.

    
asked by anonymous 11.08.2016 / 15:27

1 answer

1

You need to create the EntityManagerFactory from Hibernate / JPA.

But what is the need to use EntityManager? The Session provides everything you need and even more functions.

But it would be something like:

EntityManagerFactory factory = Persistence.createEntityManagerFactory("entidade");

EntityManager manager = factory.createEntityManager();

But if it is only because of a pure SQL query it is possible to do by Session. Just use something like:

Query query = session.createSQLQuery("select colunas from tabela");
    
11.08.2016 / 16:39