Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return the size of the greatest 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 an SQL query which will return the size of the greatest authors collection. How can I do this?

EDIT: To those who suggest using a for loop, this is how I want the answer to look like:

@Override
public int getLargestAuthors() {
return entityManager.createQuery("select b.authors from BookImpl b where b.authors.size ...").getSingleResult().size();
}
like image 893
Vladislav Avatar asked Dec 11 '25 01:12

Vladislav


2 Answers

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

select MAX(b.authors.size) from BookImpl b
like image 179
Jon1 Avatar answered Dec 13 '25 17:12

Jon1


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

This returns one or more BookImp's that have the greatest size.

like image 27
pL4Gu33 Avatar answered Dec 13 '25 16:12

pL4Gu33



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!