title: Spring data jpa sort by nested object collection size
body: <p>I am using a spring boot application and there exists the following 2 entities.</p>
  
  <p><strong>Person.java</strong></p>
  
  <pre><code>@Entity
  @Data
  @EqualsAndHashCode(callSuper = true)
  @AllArgsConstructor
  @NoArgsConstructor
  @Table(name = "PERSON")
  public class Person extends BaseEntity {
      @NotNull
      @Enumerated(EnumType.STRING)
      private StatusType status;
  
      @JsonIgnore
      @ManyToMany(fetch = FetchType.EAGER)
      @JoinTable(
              name = "PERSON_ADDRESS",
              joinColumns = @JoinColumn(
                      name = "person_id", referencedColumnName = "id"),
              inverseJoinColumns = @JoinColumn(
                      name = "address_id", referencedColumnName = "id"))
      private Collection&lt;Info&gt; addresses;
  }
  </code></pre>
  
  <p><strong>Address.java</strong></p>
  
  <pre><code>@Entity
  @Data
  @EqualsAndHashCode(callSuper = true)
  @AllArgsConstructor
  @NoArgsConstructor
  @Table(name = "ADDRESS")
  public class Address extends BaseEntity {
      @NotNull
      private String address;
  
      @ManyToMany(mappedBy = "addresses")
      private Collection&lt;Person&gt; persons;
  }
  </code></pre>
  
  <p>I am using a <code>JpaRepository</code> as follows.</p>
  
  <pre><code>@Repository
  public interface PersonRepository extends JpaRepository&lt;Person, Long&gt; {
  }
  </code></pre>
  
  <p>And I use the following statement to implement the pagination and sorting.</p>
  
  <pre><code>Page&lt;Person&gt; allPersons = personRepository.findAll(pageable);
  </code></pre>
  
  <p>where <code>pageable</code> is an instance of <code>org.springframework.data.domain.Pageable</code>.</p>
  
  <p>I am able to sort using the other columns in <code>Person</code>. But I want to sort based on the addresses collection, based on the number of <code>Address</code> record for each <code>Person</code> entity.</p>
  
  <p>In short, I wanted to sort the Persons <strong>based on the collection size of Collection</strong>. The sorting order (ASC or DESC) comes from the front end.</p>
  
  <p>Any idea how the <code>Pageable</code> object should look like to implement this? Also without returning any duplicate <code>Person</code> record if more than one <code>Address</code> exist for a <code>Person</code>.</p>