#StackBounty: #java #performance #hibernate #join #hibernate-criteria How to get batching using the old hibernate criteria?

Bounty: 200

I’m still using the old org.hibernate.Criteria and get more and more confused about fetch modes. In various queries, I need all of the following variants, so I can’t control it via annotations. I’m just switching everything to @ManyToOne(fetch=FetchType.LAZY), as otherwise, there’s no change to change anything in the query.

What I could find so far either concerns HQL or JPA2 or offers just two choices, but I need it for the old criteria and for (at least) the following three cases:

  • Do a JOIN, and fetch from both tables. This is OK unless the data is too redundant (e.g., the master data is big or repeated many times in the result). In SQL, I’d write
    SELECT * FROM item JOIN order on item.order_id = order.id
    WHERE ...;
  • Do a JOIN, fetch from the first table, and the separation from the other. This is usually the more efficient variant of the previous query. In SQL, I’d write
    SELECT item.* FROM item JOIN order on item.order_id = order.id
    WHERE ...;

    SELECT order.* FROM order WHERE ...;
  • Do a JOIN, but do not fetch the joined table. This is useful e.g., for sorting based on data the other table. In SQL, I’d write
    SELECT item.* FROM item JOIN order on item.order_id = order.id
    WHERE ...
    ORDER BY order.name, item.name;

It looks like without explicitly specifying fetch=FetchType.LAZY, everything gets fetched eagerly as in the first case, which is sometimes too bad. I guess, using Criteria#setFetchMode, I can get the third case. I haven’t tried it out yet, as I’m still missing the second case. I know that it’s somehow possible, as there’s the @BatchSize annotation.

  • Am I right with the above?
  • Is there a way how to get the second case with the old criteria?

Update

It looks like using createAlias() leads to fetching everything eagerly. There are some overloads allowing to specify the JoinType, but I’d need to specify the fetch type. Now, I’m confused even more.


Get this bounty!!!

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.