0
votes

I'm unsure how to explain the following: My table has a self-referential pointer to another row within the same table by ID, e.g.

@Entity  
@Table(name = "questions_t", schema = "public")
public class QuestionsT implements java.io.Serializable {

     private QuestionsT relatedQuestion;

     //...
     @ManyToOne(fetch = FetchType.LAZY)
     @JoinColumn(name = "related_question_id")
     public QuestionsT getRelatedQuestion() {
             return relatedQuestion;
     }
 }

The Fetch Strategy is FetchType.LAZY.

But nonetheless, after getting a list of initial Questions in my app, if I do this

question.getRelatedQuestion().getSomeProperty()

the property of a related question comes back correct and filled-out. This is not what I expected with LAZY. I expected that the original Question object's Parent Question would have a minimally filled out body (maybe with just the ID), but any further info about the Related Question (a child object) would require an extra manual fetch.

I see that when I execute the get Property, Hibernate does 1 Select behind the scenes -- is that automatic?

1
Lazy means "not until accessed" when you say question.getRelatedQuestion().<anything> it will load it seeing that it is being accessed. If you want that manually you should do it manually and not say "ManyToOne"prajeesh kumar

1 Answers

1
votes

What you explained is completely normal. After you try to access a property on the lazy object, Hibernate will automatically load it.

Please take a look at my blog post for further info.

https://arnoldgalovics.com/lazyinitializationexception-demystified/