Unable to close the Hibernate Session for loading Lazily loaded fields

130 views Asked by At

We are using Hibernate+Spring for a module and we used @ManyToOne(fetch = FetchType.LAZY) on multiple fields in multiple POJOs. While querying for these POJOs through HQL, I am opening a HibernateSession and returning the result from the DAO method. I wasn't closing these HibernateSesions because i couldn't get the FK objects through getter methods.

Here is one of the simplest methods we implemented :

public List<QmsCapaWfUserDetails> getCapaWfUserDetailsesByWfIdsList(List<Integer> wfIdsList) {
        logger.debug("QmsCapaDao getCapaWfUserDetailsesByWfIdsList() Start");
        List<QmsCapaWfUserDetails> capaWfUserDetailses = null;
        if (!Utilities.IsEmpty(wfIdsList)) {
            StringBuffer hqlQuery = null;
            Query query = null;
            Session hibernateSession = sessionFactory.openSession();
            hqlQuery = new StringBuffer();
            hqlQuery.append("From QmsCapaWfUserDetails capaWfUserDetails where capaWfUserDetails.capaWfDetails.id in (:wfIdsList) ");
            query = hibernateSession.createQuery(hqlQuery.toString());
            if (query != null) {
                query.setParameterList("wfIdsList", wfIdsList);
            }
            capaWfUserDetailses = query.list();
            hibernateSession.flush();
        }
        logger.debug("QmsCapaDao getCapaWfUserDetailsesByWfIdsList() End");
        return capaWfUserDetailses;
    }

I thought flushing these sessions could do something. But it appears not.

I know that because of these too many open sessions, our application has frozen. If i close these sessions, i can't access the lazily loaded FKs.

What could be the best solution..!?

1

There are 1 answers

4
Nico On

As already mentioned by Deinum, you should use sessionFactory.getCurrentSession() instead of sessionFactory.openSession().

For a detailed comparison between this methods, read here.

If you really don't want to let your sessions managed by Hibernate directly and want to close it yourself have a look here.