Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In which cases the return type is java.math.BigDecimal for a native query with "Select count(columnName) ..."

Tags:

java

sql

jpa

I'm using a native query like this:

public Long count() {  
String sql = "SELECT COUNT(t.task_id_t100) from T100_TASK t ";  
Query query = entityManager.createNativeQuery(sql);  
return (Long) query.getSingleResult();  
} 

This always worked. Today I got a ClassCastException because query.getSingleResult() returned a BigDecimal. I can't remember to have changed anything.

The hint in this answer tells Note that in some cases result type may depend on the database, i.e. it can be something like BigDecimal

In which cases?

like image 570
Ali Atilgan Avatar asked Nov 29 '25 18:11

Ali Atilgan


1 Answers

you can simply ask the object which 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 - a bigDecimal can be much bigger than a long can be... (can be.. not guaranteed)

like image 149
Martin Frank Avatar answered Dec 01 '25 08:12

Martin Frank



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!