Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

hibernate returning BigDecimal datatype instead of long

The hibernate named query returns a BigDecimal for a column that has datatype NUMBER.

select col1 as "col1" from table1 union select col2 as "col1" from table2

On client side, I expect the datatype of col1 to be long (primitive) I do this:

<return-scalar column="col1" type="java.lang.Long" />

or

<return-scalar column="col1" type="long" />

In both cases, I get :

java.lang.ClassCastException: java.math.BigDecimal incompatible with java.lang.Long

How can I fix this? My suspiscion, something wrong with the aliasing?

like image 884
Victor Avatar asked Mar 21 '11 15:03

Victor


2 Answers

Oracle NUMBER maps to BigDecimal in Hibernate by default. Try setting the type to BigDecimal.

like image 151
dseibert Avatar answered Oct 02 '22 13:10

dseibert


I don't know what the issue is with your hibernate configuration but as a workaround, one trick that allows you not to care what java Number type a Hibernate query returns is to cast the returned value to Number and call .longValue():

long id = ((Number) em.createNativeQuery("select my_seq.nextVal from dual")
              .getSingleResult())
          .longValue();

That way you don't care if the query returns Long, BigDecimal, BigInteger, Short as long as it fits into a java long.

like image 38
Dave Moten Avatar answered Oct 02 '22 14:10

Dave Moten