简体   繁体   中英

How to resolve java.lang.ClassCastException while processing Sys refcursor?

I have the below code

StoredProcedureQuery storedProcedure = em.createStoredProcedureQuery("pkg_p.proc_p");
         storedProcedure.getResultList();

stored proc returns a ref cursor equivalent to the below query

 select 1 as id_col, 'My Name ' as name , 1000 as sal from dual;

I have a pojo class MyTable which is equivalent to the result set return type of the query

 public class MyTable {
 private Long idCol;
 private String name;
 private Long sal;

 /// setter and getters omitted for brevity

}

for(Object[]row: resultSet)
        {
MyTable mt = new MyTable ();
mt.setIdCol((Long)row[0]);  ///throw class cast exception
}

How to resolve the below error

Request processing failed; nested exception is java.lang.ClassCastException: java.math.BigDecimal cannot be cast to java.lang.Long

Even though row[0] has Long values like 1,2,10,687 etc

You can't cast Big Decimal to Long how ever you can get the Long value from it using

row[0].longValue()

if that doesn't work cast row to big decimal and

(BigDecimal) row[0].longValue()

so your code would look something like this

mt.setIdCol((BigDecimal)row[0].longValue());

or try to change the loop to

for(BigDecimal[] row : resultSet)

if you don't want to use casting

after reading your comments.

    for(Object[] row: resultSet) {
        MyTable mt = new MyTable();
        if(resultSet instanceof BigDecimal) {
            mt.setIdCol((BigDecimal)row[0].longValue());
        } else if (resultSet instanceof String){
            ....
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM