1

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 -

  1. What is the easiest way to fetch only ACTIVE children?
  2. Is it possible to set ACTIVE query condition on the Child entity's status property to fetch only active child entities by default?
  3. Will something like above query method work?

1 Answer 1

1
  1. See below
  2. It's not possible with Spring annotations alone, but you can achieve it with Hibernate's @Where:
@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; } 
  1. Your query method would not work, Spring Data wouldn't understand the method name. To make it work, the 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=? 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.