Minutis Minutis - 7 months ago 88
Java Question

JPA count NamedQuery

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

Change your code likes this;

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