How do I return the size of the largest collection in JPA?

Here's my code:

@Entity
@Table("Books")
public class BookImp implements Book {

@Id
@GeneratedValue
@Column(name = "id")
private Long id;

@ElementCollection
private Set<String> authors = new HashSet<String>();

// getters + constructors

}

      

I want to create a SQL query that will return the size of the largest collection of authors. How can i do this?

EDIT: For anyone suggesting using a for loop, this is how I want the answer to look like this:

@Override
public int getLargestAuthors() {
return entityManager.createQuery("select b.authors from BookImpl b where b.authors.size ...").getSingleResult().size();
}

      

+3


source to share


2 answers


Not a mysql wizard, but you can't do it like this?



select MAX(b.authors.size) from BookImpl b

      

+3


source


SELECT m FROM BookImp m where size(m.authors) = (select max(size(c.authors)) FROM BookImp c)



This returns one or more BookImp instances with the largest size.

+2


source







All Articles