1

One of our model object in our application has many fields configured to be eagerly fetched like so:

@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "field")
public Field getField() {
    return this.field;
}

However I sometime do not need these information, which slow down my queries for nothing. I cannot change the behaviour and use FetchType.LAZY instead as I've no idea what will be the impact on the whole application (legacy...). Is there a way to simply tell hibernate to fetch nothing, except if it is specified in the query?

Flanfl
  • 516
  • 8
  • 29

2 Answers2

0

Last time I checked there was no proper solution provided by hibernate, so I ended up with this solution:

  • Configured the problematic references as LAZY.
  • All affected service methods (that used these models) got an overloaded version with boolean forceEager
  • by default all existing functions were refactored to call the new ones with forceEager=true
  • and here comes the trick: as a means of "forcing the eager fetching" I found nothing better than actually accessing the proxied (lazy-fetched) objects. In case for example a lazily referenced list doing list.size() will force Hibernate to load the full list, hence the service returns with fully fetched object.

In case of more than one layer in your objectstructure is affected, you need to traverse through the whole hierarchy and access every lazily loaded object from top to bottom.

This is a bit error-prone solution, so you need to handle it with care.

Gergely Bacso
  • 14,243
  • 2
  • 44
  • 64
0

If its possible to switch to Criteria for this query, you could use FetchMode.SELECT for the field property

crit.setFetchMode("field", FetchMode.SELECT); 
Marius
  • 3,043
  • 1
  • 15
  • 24
  • Thanks for you repl. I tried it but nothing changed, I still have many SELECT queries. I think my only solution will be to leave it as or change everything to LAZY and correct all broken codes... – Flanfl Dec 07 '15 at 09:35