I have entities that have transitive relationships. So Entity A is mapped OneToMany to entity B and entity B is mapped OneToMany with entity C. Entity A has a property, userID, which is NOT the primary key and I need to fetch all records for a user ID from the DB. Due to the requirements, I want to fetch the child records of A and B eagerly. I have annotated the entities with FetchMode join and my Repository has a method findByUserId(int userId). I am using spring data JPA with hibernate as underlying ORM. Executing the above query method fires multiple queries, though I expected only one query with join to be fired.
I have already tried EntityGraphs, annotated my repository method with NamedQuery, tried mapping entities ManyToOne bidirectional but nothing seems to be working.
@Entity
@Table(name = "A_Master")
public class EntityA{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private Long id;
private int userId;
@OneToMany(cascade = CascadeType.PERSIST)
@JoinColumn(name = "FK_reservationId")
@Fetch(FetchMode.JOIN)
private List<EntityB> bEntities= new ArrayList<>();
}
@Entity
@Table(name = "Entity_B")
public class EntityB{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private Long id;
@OneToMany(cascade = CascadeType.PERSIST)
@JoinColumn(name = "FK_journeyId")
@Fetch(FetchMode.JOIN)
private List<EntityC> cEntities = new ArrayList<>();
}
public interface ReservationRepository extends JpaRepository<EntityA, Integer>
{
public List<EntityA> findByUserIdAndStatus(String userId);
}