Moonlit
Moonlit

Reputation: 5409

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

Upvotes: 2

Views: 2702

Answers (1)

Mikko Maunu
Mikko Maunu

Reputation: 42114

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.

Upvotes: 4

Related Questions