When is the return type java.math.BigDecimal for a custom query with "Select count (columnName) ..."
I am using my own query:
public Long count() {
String sql = "SELECT COUNT(t.task_id_t100) from T100_TASK t ";
Query query = entityManager.createNativeQuery(sql);
return (Long) query.getSingleResult();
}
It always worked. Today I received ClassCastException
because I query.getSingleResult()
returned BigDecimal
. I cannot change anything.
The hint in this answer saysNote that in some cases result type may depend on the database, i.e. it can be something like BigDecimal
In which cases?
+3
source to share
1 answer
you can just ask the object whose class it is ...
public Long count() {
String sql = "SELECT COUNT(t.task_id_t100) from T100_TASK t ";
Query query = entityManager.createNativeQuery(sql);
Object o = query.getSingleResult();
//for BigDecimal
if (o.getClass().equals(BigDecimal.class) ){
BigDecimal big = (BigDecimal) o;
return handleBigDecimal(big); //TODO
}
//other types might follow
return (Long) o;
}
but remember that bigDecimal can be much larger than long can be ... (maybe .. not guaranteed)
+1
source to share