Disable Lazy Loading in Hibernate

可紊 提交于 2019-12-23 07:50:39

问题


How do I disable lazy loading in Hibernate? I am using persistence annotations, not an hbm xml file.

I am fetching a single object by ID and want all properties loaded. The session is closed before I use the object.

Thanks!


回答1:


You need to annotate the properties that you want non-lazy loaded with FetchType.EAGER

   @ManyToOne(fetch = FetchType.EAGER)

You see, it isn't the object that you are loading that is lazy loaded. Rather, that object's associations are lazy, and you need to tell them not to be if that is your desired behavior.

If those objects also have associations that you want loaded eagerly, you need to annotate them as well.




回答2:


You could specify fetch = FetchType.EAGER on all your associations, recursively, but this would load a whole bunch of data you're probably not interested in.

It's usually a better solution to at least let all OneToMany and ManyToMany associations to LAZY (which is the default), and initialize them before closing the session if your use-case needs them (or even load them with an ad-hoc query).

OneToOne and ManyToOne associations are EAGER by default, and this already often generates too many requests. I usually prefer to mark everything lazy, unless all the use-cases need to fetch the association.




回答3:


Use fetch = FetchType.EAGER for all collection and entity that you want lazy to be off.

Also Check this out: http://techblog.bozho.net/?p=645



来源:https://stackoverflow.com/questions/5479140/disable-lazy-loading-in-hibernate

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