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?
getSingleResult. Execute a SELECT query that returns a single untyped result.
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 .
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();
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