Using DetachedCriteria get Result with another Table

How to use Hibernate’s DetachedCriteria to get result by using Join for a class. As of newest Hibernate, the type Expression is deprecated and that’s where Restrictions come into place.

Hibernate Title

Let’s say a HQL query like this.

List list = hibernateTemplate.getSessionFactory().getCurrentSession().createQuery(“from Function fn where fn.createdByStaff=loginStaff and fn.prospect.processTypeId in (‘1′,’4′,’5’)”).list();

Now let’s try using DetachedCriteria to solve this.

DetachedCriteria criteria = DetachedCriteria.forClass(Function.class).add(Restrictions.eq(“createdByStaff”, loginStaff)).createCriteria(“prospect”, “prospect”).add(Restrictions.in(“prospect.processTypeId”, processTypes));

Then let’s say I need to set max size to 100 or any other amount.

List list = hibernateTemplate.findByCriteria(criteria,0,100);

It’s done. Simple to use. One reason to use a max size is so that one doesn’t fetch the whole table and result in Java Heapspace Out of Memory issue.

What’s the difference then by using HQL and Criterias?

Criteria respects the laziness settings in your mappings and guarantees that what you want loaded is loaded. This means one Criteria query might result in several SQL immediate SELECT statements to fetch the subgraph with all non-lazy mapped associations and collections. If you want to change the “how” and even the “what”, use setFetchMode() to enable or disable outer join fetching for a particular collection or association. Criteria queries also completely respect the fetching strategy (join vs select vs subselect).

HQL respects the laziness settings in your mappings and guarantees that what you want loaded is loaded. This means one HQL query might result in several SQL immediate SELECT statements to fetch the subgraph with all non-lazy mapped associations and collections. If you want to change the “how” and even the “what”, use LEFT JOIN FETCH to enable outer-join fetching for a particular collection or nullable many-to-one or one-to-one association, or JOIN FETCH to enable inner join fetching for a non-nullable many-to-one or one-to-one association. HQL queries do not respect any fetch=”join” defined in the mapping document.

Source from http://www.hibernate.org/315.html

Now the last line of each paragraph tells the main difference of the HQL and Criteria search of the Hibernate.

2 Comments

  1. mohan July 15, 2011
  2. mohan July 15, 2011

Leave a Reply to mohan Cancel reply