Search code examples
javajpanamed

JPA named query to get size of a collection


I have the following two entities:

@Entity
class Relation{

@ManyToOne
private User user;

//some other fields

...
}

The user entity has a collection of other entities:

@Entity
class User {

@OneToMany(mappedBy="user")
private Collection<Address> addresses = new ArrayList<Address>();
}

//some other fields

}

Is it possible to write a named query in the Relation entity which gives me the users which have more than 2 addresses...? like:

@NamedQuery("SELECT m from Membership m where m.otherfield = ?1 AND m.user.addresses > 2")

in other words, how can i get the size of this entity with a named query?

thx


Solution

  • In JPQL query SIZE function can be used to get size of collection. It takes path to the collection as argument and returns number of elements.