Counting Records using a JPQL Query defined in a @NamedQuery
Here is a quick tip which shows how you can count your Database records using a NamedQuery in JPA. Here is the Named Query:
@NamedQuery(name="Orders.countAll", query="SELECT COUNT(o) FROM Orders o")
Then, you can run the Named Query from any class which has access to the Entity Manager:
public Number countAll() { return ((Number)entityManager.createNamedQuery("Orders.countAll").getSingleResult()).intValue(); }