Overriding Hibernate FetchMode with both Criteria and HQL

By Eugenia Pérez | 25 February, 2015

When using Hibernate the most common way to flag the associations Fetch strategy is by using the Lazy or Eager mode which can be established either with annotations or XML mapping files.

It is true that we can map or annotate this Fetching strategy  within the source code, for instance: @ManyToMany (fetch = FetchType.EAGER) or lazy = “false” in XML, but it is also true that when we have a complex model with chaining dependent collections, problems usually arise when checking this by default.

However this default strategy can be override from a specific method that access the database. This can be done in HQL and Criteria using the FetchMode clause. By doing this we are changing the strategy for only that specific interaction with the database. An example of each method can be found below:

While in Criteria, the problem of the Lazy collection Compras was solved with the setFetchMode method, in HQL flagging a JOIN operation as Fetch to solve this becomes possible:

Take a look to my slides just in case of requiring further information:

facebooktwittergoogle_plusredditpinterestlinkedinmailby feather