Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Learn more about Collectives
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Learn more about Teams
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?
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();
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();
public int returnCountOfDogTable(String id) {
//...
List<BigDecimal> resultList = query.getResultList();
BigDecimal result = resultList.get(0);
return result.toIntValue();
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;
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.