Oracle Mokey
Oracle Mokey

Reputation: 81

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

Upvotes: 0

Views: 273

Answers (1)

SamHoque
SamHoque

Reputation: 3154

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){
            ....
        }
    }

Upvotes: 2

Related Questions