Search code examples
javaspring-bootspring-data-jpaprojection

Get count of children based on their property via Projection


In my project I have a parent and a child entity. The child has a property 'isDeleted' which is used to include or exclude that record from the total count. A projection is written to get parent and a method is declared with @Value("#{target.getChildren().size()}") to get the children count. How do I exclude the children with isDeleted==1 in the SpEL syntax? 0 denotes 'active' and 1 denotes 'deleted'.

Parent

@Entity
public class Parent {
   long id;
   Set<Child> children;

   public Set<Child> getChildren();
}

Child

public class Child {
   int isDeleted;

   public int getIsDeleted();
}

Projection

public interface ParentProjection {
    Long getId();
    @Value("#{target.getChildren().size()}")
    int getChildrenCount();
}

Solution

  • in XML based SpEL we can filter list like following:

    <property name="failedStudents" value="#{studentList.?[marks lt 40]}" />
    

    you can try making such expression for your children class eg: @Value("#{target.getChildren().?[isDeleted eq 1].size()}")