开发者

Disable Lazy Loading in Hibernate

开发者 https://www.devze.com 2023-02-21 03:51 出处:网络
How do I disable lazy loading in Hibernate?I am using persistence annotations,not an开发者_高级运维 hbm xml file.

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!


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.


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.


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


Write fetch = FetchType.EAGER in oneToMany annotation.

like this : @OneToMany(fetch = FetchType.EAGER)

Attention: if your database is so big with many relations, it can Increase your database process very much;

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号