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

Asked

Viewed 700 times

0

I work 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 as standard the session factory

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

Thus 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 started to have the need to use an Entitymanager to create a custom query where returns me a list of uncharted object in Hibernate...

Catch a Session from an Entitymanager already found.

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

But get an Entitymanager from a Session not yet.

I wonder if it is possible to transform, recover or even create an Entitymanager from a Session.

Thank you very much.

1 answer

1

It is necessary to create Entitymanagerfactory from Hibernate/JPA.

But what is the need to use Entitymanager? 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");
  • In fact whenever I searched for custom queries I found the query.getResultList() command so I was trying to use Entitymanager to load the list. Because I had already tried to load Session and could not. But now I managed with List<Object[]> result = query.list(). Thank you very much.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.