Reputation: 4602
I have a Parent
and Child
entities like below -
class Parent {
Long id;
List<Child> children;
}
class Child {
Long id;
String status; // ACTIVE or INACTIVE
Parent parent;
}
I would like to fetch the parent
along with all its children
having status=ACTIVE
property.
public interface ParentRepository<Parent, Long> {
Parent findByIdAndChildStatus(@Param("id") id, @Param("childStatus") status);
}
Question is -
ACTIVE
children?Child
entity's
status
property to fetch only active child entities by default?Upvotes: 1
Views: 1814
Reputation: 10651
@Entity
@Getter
@Setter
public class Parent {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE)
private Long id;
@Where(clause = "status='ACTIVE'")
@OneToMany(mappedBy = "parent", cascade = CascadeType.ALL)
private List<Child> children;
}
Child
entity would need to be in the plural form:public interface ParentRepository extends CrudRepository<Parent, Long> {
Parent findByIdAndChildrenStatus(Long id, String status);
}
Unfortunately, the meaning of the method would be a bit different than expected. It would mean: get Parent with the id id
and having a Child with the status status
. The generated query looks as follows:
SELECT parent0_.id AS id1_1_
FROM parent parent0_
LEFT OUTER JOIN child children1_ ON parent0_.id=children1_.parent_id
WHERE parent0_.id=? AND children1_.status=?
Upvotes: 1