Like the below class one parent can have multiple children i want to fetch only one child along with parent
class entity Parent{
@OneToMany
private Set<Child> children;
}
Like the below class one parent can have multiple children i want to fetch only one child along with parent
class entity Parent{
@OneToMany
private Set<Child> children;
}
One way you can do this is to also specify a relationship to Parent in the Child and used mappedBy in your OnetoMany relationship to specify that the Child is the owner of the relationship
Child relationship to Parent
@ManyToOne
@JoinColumn(name = "parent_id")
private Parent parent;
Updated relationship in Parent
@OneToMany(mappedBy = "parent")
private Set<Child> children;
Create a ChildRepository and fetch the child by Id which will also (Eagerly) fetch the parent
repository.findById(Long childId);
Eager fetching is not really recommended, but that is the default with @ManytoOne. Better to mark it with FetchType.LAZY and fetch child and parent in a single query
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "parent_id")
private Parent parent;
Add query to ChildRepository
@Query("SELECT c FROM Child c LEFT JOIN FETCH c.parent WHERE c.id = :childId)
Optional<Child> fetchChildAndParent(@Param("childId") Long childId);