javahibernatejpacreatecriteriacreatequery

JPA createQuery working but createCriteria not working session is closed error


I am trying to use Criteria API from Hibernate by getting hibernate session from EntityManager as following

public org.hibernate.Criteria getCriteria() {
    HibernateEntityManager hem = em.unwrap(HibernateEntityManager.class);
    org.hibernate.Session session = hem.getSession();
    return session.createCriteria(getEntityBeanType());
}

In createCriteria return I am getting "session is closed error".

From the same point of code where I call getCriteria if I call createQuery method as

getEntityManager().createQuery(".....");

It is working fine and I can do select on database.

I want to use Hibernate Criteria API becuase I am comfortable with it.


Solution

  • Make sure if your session is open before you create criteria

    public org.hibernate.Criteria getCriteria() {
    
        HibernateEntityManager hem = em.unwrap(HibernateEntityManager.class);
        org.hibernate.Session session = hem.getSession();
    
     if(session.isOpen())
    {
    return session.createCriteria(getEntityBeanType())
    }
    
        return null;
    }
    

    Check your log for more information and share the same here and it will be helpful for us to debug...