Returning result of count native query using EntityManager in Java?
Asked Answered
P

4

12

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?

Paraffin answered 4/10, 2016 at 16:13 Comment(0)
P
35

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();
Pongee answered 7/8, 2018 at 19:55 Comment(0)
C
14

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();
Carrelli answered 4/10, 2016 at 16:26 Comment(0)
M
3

Simply try this:

public int returnCountOfDogTable(String id) {
//...
    List<BigDecimal> resultList = query.getResultList();
    BigDecimal result = resultList.get(0);
    return result.toIntValue();
}
Mcglothlin answered 4/10, 2016 at 16:15 Comment(2)
ok, and how to then change big decimal back to int in return value?Paraffin
perhaps result.toIntValue() ?Mcglothlin
S
-1
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

@PersistenceContext
protected EntityManager em;

public int getCountQuery(String sql) {
    int resultCount = 0;
    try {
        Query query = em.createNativeQuery(sql);
        resultCount = ((Number) query.getSingleResult()).intValue();
    } catch (Exception e) {
        log.error("SQL Error" + e.getMessage());
    }
    return resultCount;
}
Scrunch answered 20/1, 2022 at 5:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.