Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning result of count native query using EntityManager in Java?

I have the following SQL Query :

SELECT COUNT(*) FROM DOG where ID = 'SampleId';

I am trying to write this in java :

public int returnCountOfDogTable(String id){

        String sql= "SELECT COUNT(*) FROM DOG WHERE ID =:id";
        Query query = persistence.entityManager().createNativeQuery(sql);
        query.setParameter("id", id);
        List<Integer> resultList = query.getResultList();
        int result = resultList.get(0);
        return result;
    }

However I get this exception:

java.lang.ClassCastException: java.math.BigDecimal cannot be cast to java.lang.Integer

How can I solve this?

like image 843
java123999 Avatar asked Oct 04 '16 16:10

java123999


People also ask

What does getSingleResult return?

getSingleResult. Execute a SELECT query that returns a single untyped result.

How do you return a map result from a JPA or Hibernate query?

If a given JPA GROUP BY query returns only two columns where one is unique, it's very suitable to return the result as a Java Map. For this, you can use either the Java Stream functionality or the Hibernate-specific ResultTransformer .


2 Answers

You can also use Number and call intValue():

Query query = entityManager.createNativeQuery("SELECT COUNT(*) FROM DOG WHERE ID =:id");
query.setParameter("id", 1);
int count = ((Number) query.getSingleResult()).intValue();
like image 147
Dherik Avatar answered Oct 03 '22 02:10

Dherik


Make sense to use Query#getSingleResult method:

Query query = entityManager.createNativeQuery("SELECT COUNT(*) FROM DOG WHERE ID =:id");
query.setParameter("id", 1);
int count = ((BigInteger) query.getSingleResult()).intValue();
like image 24
Boris Avatar answered Oct 03 '22 04:10

Boris