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!

1
  • My addition to this question: How can I disable lazy loading in a way that instead of proxies, empty collections would appear? Commented Jan 22, 2013 at 1:59

4 Answers 4

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

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

Comments

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;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.