Hibernate OneToMany FetchType.LAZY is not working unless accessing the collection?

微笑、不失礼 提交于 2019-12-05 17:36:45
ujulu

market.getChannelGroups(); // this is not working, market's channelGroups is still empty.

The reason why this is happening might be the market.getChannelGroups() call is returning a proxy because of the lazy loading. The actual loading will happen when you call a method on the returned object which in this case is channel groups collection. So to trigger the loading of the entities into the collection you have to call the following, for example:

market.getChannelGroups().size();

Now why is the following call working?

System.out.println(market.getChannelGroups());

The reason will be clear if you understand how System.out.println() is working, namely, it is calling the toString() method on the passed in object which in this case is equivalent to the following:

System.out.println(market.getChannelGroups().toString());

Here is the JavaDoc for the println(Object) method:

Prints an Object and then terminate the line. This method calls at first String.valueOf(x) to get the printed object's string value, then behaves as though it invokes print(String) and then println().

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