1

I assume that the following is a no no(?)

> public Criteria createCritera(Class<?> persistentClass) { 
>     ...//creation of session object etc.
>     session.beginTransaction();
>     Criteria crit = session.createCriteria(persistentClass);
>     session.getTransaction().commit();
>     session.close();
>     
>     return crit; 
}

OR is it ok to use and manipulate a Critera object even though the Session object used to create th Critera is closed and the current Transaction is commited.

3 Answers 3

3

This won't be a good idea indeed ...

I am not sure about what you're trying to accomplish, but I think you should have a look at the DetachedCriteria class.

This allows you to create a Criteria query that is not linked / connected to a Session. When you want to execute the DetachedCriteria, you have to attach it to a session, and you're good to go.

Sign up to request clarification or add additional context in comments.

Comments

3

Use DetachedCriteria if you don't have an active Session to work with. Later on (say, in a DAO where you have an active Session for executing the query) you can use DetachedCriteria#getExecutableCriteria to get an executable Criteria.

Comments

0

If you try to manipulate a Query/Critera after the session, that created the Query/Critera, is closed you will get a HibernateException thrown at you. The exception will say: "session is closed".

So if the Detached technique is not applicable i would recommend (myself) to always return the result, eg.

crit.list();
query.list();

instead of returing the Critera/Query instance

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.