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
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.
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.
Change your code likes this;
int count = ((Number)em.createNamedQuery("Charakteristika.findAllCount").getSingleResult()).intValue(); System.out.println(count);
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(); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With