Returning result of count native query using EntityManager in Java?

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP



Returning result of count native query using EntityManager in Java?



I have the following SQL Query :


SQL Query :


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



I am trying to write this in java :


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?




3 Answers
3



Simply try this:


public int returnCountOfDogTable(String id)
//...
List<BigDecimal> resultList = query.getResultList();
BigDecimal result = resultList.get(0);
return result.toIntValue();





ok, and how to then change big decimal back to int in return value?
– java123999
Oct 4 '16 at 16:16





perhaps result.toIntValue() ?
– Shark
Oct 4 '16 at 16:17


result.toIntValue()



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();



You can also use Number and call intValue():


Number


intValue()


Query query = entityManager.createNativeQuery("SELECT COUNT(*) FROM DOG WHERE ID =:id");
query.setParameter("id", 1);
int count = ((Number) query.getSingleResult()).intValue();;






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

Firebase Auth - with Email and Password - Check user already registered

Dynamically update html content plain JS

How to determine optimal route across keyboard