Hibernate : Force lazy-loadding on eager field

杀马特。学长 韩版系。学妹 提交于 2019-12-11 11:56:32

问题


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?


回答1:


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.




回答2:


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

crit.setFetchMode("field", FetchMode.SELECT); 


来源:https://stackoverflow.com/questions/33959677/hibernate-force-lazy-loadding-on-eager-field

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!