Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 
like image 433
Minutis Avatar asked Aug 10 '12 06:08

Minutis


People also ask

How does JPA get count of records?

count() repository method If you want to know the total number of rows available in the entity table, use the count derived method of the CrudRepository interface. For example, the following getCustomerCount method retrieves the number of entities available in the table using the method count.

How do you write a count query in JPA repository?

You can easily do so by using the derived count query available in the CrudRepository since the JpaRepository interface extends the CrudRepositoy . For example, the following countByNewUser is a derived count query. The Customer database contains a new_user column that holds either 0 or 1.


2 Answers

Change your code likes this;

      int count = ((Number)em.createNamedQuery("Charakteristika.findAllCount").getSingleResult()).intValue();       System.out.println(count); 
like image 77
Sai Ye Yan Naing Aye Avatar answered Sep 17 '22 13:09

Sai Ye Yan Naing Aye


Also you can try it: use TypeQuery interface with Long value. In the next example, "PosicionHistorialDia.findNumberSpeeding" query is a jpa count.

    @Override     public Long findCount(String eventCode) {          TypedQuery<Long> query = em.createNamedQuery(             "PosicionHistorialDia.findNumberSpeeding",             Long.class);         query.setParameter("event", eventCode);         return query.getSingleResult();     } 
like image 28
Gaalvarez Avatar answered Sep 17 '22 13:09

Gaalvarez