JPA count NamedQuery

Minutis picture Minutis · Aug 10, 2012 · Viewed 62.7k times · Source

how to get count with a namedquery, without getting all the list (it would increase performance I think). This is the named query that doesn't work:

@NamedQuery(name = "Charakteristika.findAllCount", query = "SELECT COUNT(c) FROM Charakteristika c")

Executing this:

System.out.println("a");
System.out.println(em.createNamedQuery("Charakteristika.findAllCount", Integer.class).getSingleResult().intValue());
System.out.println("b");

Output:

a

Although this query works:

@NamedQuery(name = "Charakteristika.findAll", query = "SELECT c FROM Charakteristika c")

Executing this:

System.out.println("a");
System.out.println(em.createNamedQuery("Charakteristika.findAll", Charakteristika.class).getResultList().size());
System.out.println("b");

Output:

a
11111
b

Answer

Sai Ye Yan Naing Aye picture Sai Ye Yan Naing Aye · Aug 10, 2012

Change your code likes this;

      int count = ((Number)em.createNamedQuery("Charakteristika.findAllCount").getSingleResult()).intValue();
      System.out.println(count);