I have the following problem (pseudo-java-code):
Let me a class A,B,C with the following relationships:
@Entity
@Table(name = "A")
public class A {
@OneToMany(mappedBy = "a")
private B b;
}
@Entity
@Table(name = "B")
public class B {
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "a_id")
private A a;
@OneToOne(mappedBy = "b", fetch = FetchType.LAZY)
private C c;
}
@Entity
@Table(name = "C")
public class C {
@OneToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "b_id")
private B b;
}
I'm using JpaRepository with @Query annotation and I implemented the following query:
@Query("SELECT DISTINCT(a) FROM A a "
+ "LEFT JOIN FETCH a.b as b"
+ "WHERE a.id = :id ")
A findById(@Param("id") Integer id);
I want retrieve the informations about class A and B, but not C. Somehow (I don't know why) the query try to retrive also the relation between B and C. And then, with hibernate, start the lazy invocation for retrieving C.
Naturally, if I fetch also the relation between B and C (adding LEFT JOIN FETCH b.c as c
) that's not happen.
My question is, why? Why I'm forced to fetch all nested relations and not only the ones which I need?
thank you. Carmelo