Disable Lazy Loading in Hibernate
Asked Answered
N

4

14

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!

Nationwide answered 29/3, 2011 at 21:25 Comment(1)
My addition to this question: How can I disable lazy loading in a way that instead of proxies, empty collections would appear?Dippy
A
8

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.

Allineallis answered 29/3, 2011 at 21:30 Comment(0)
D
0

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.

Dorsad answered 29/3, 2011 at 21:34 Comment(0)
S
0

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

Sectionalize answered 17/7, 2014 at 18:14 Comment(0)
K
0

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;

Keifer answered 2/12, 2021 at 5:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.