How to get single child entity along with parent entity in spring jpa where the child entity is bound by one to many mapping like a parent having m

Viewed 24

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;
}
1 Answers

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);

Related