Hibernate Criteria and join performance when fetching only first row

I have the following code:

    Session session = openSession(FlushMode.MANUAL);
    Criteria criteria = session.createCriteria(MyClass.class);
    UserProfile profile = UserProfile.getInstance();
    Transaction tx = null;
    try {
    	criteria.add(Restrictions.eq("cond1", cond1));
    	criteria.add(Restrictions.eq("cond2", cond2));
    	criteria.setFirstResult(0);
    	criteria.setMaxResults(1);
    	criteria.setFetchMode("items", FetchMode.JOIN);
    	tx = session.beginTransaction();
    	List list = criteria.list();
    	..
    }
    ...

Here I need just the first entry hence using

    criteria.setFirstResult(0);
    criteria.setMaxResults(1);

Now I have a Join defined on “items”:

`criteria.setFetchMode("items", FetchMode.JOIN);`

How do criteria work? Will it fetch all the data matching the restrictions and do a join and then order it and return the first row?

Or does it first match restrictions, order it and fetch the first result and then do a join for that single row?

If it is former, How best can this be optimized so that the join operation won’t be performed on all the rows?

You can easily observe the behavior yourself by looking at the SQL Hibernate executes. Having said that, Hibernate will fetch all records and do in-memory pagination when you join fetch collections. Also, keep in mind that the legacy Hibernate Criteria API will be removed in 6.0 so if you want to code something future proof, you should use the JPA Criteria API instead.

1 Like