开发者

hibernate returning BigDecimal datatype instead of long

开发者 https://www.devze.com 2023-02-18 08:56 出处:网络
The hibernate named queryreturns a BigDecimal for a column that has datatype NUMBER. select col1 as \"col1\" from table1 union select col2 as \"col1\" from table2

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.ClassCastExcept开发者_JAVA技巧ion: java.math.BigDecimal incompatible with java.lang.Long

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


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


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.


Yes, Hibernate Maps Oracle Number Type to BigDecimal in Java. Since BigDecimal computations are costly in Java, once You get the BigDecimal in Java, write a Utility to convert the BigDecimal Collection to Integer or Long collection, based on Your data size.


I had the same problem. This fixes the issue neatly and returns a List of Long

List<Long> orgTypeIds = session.createSQLQuery("SELECT typeId FROM org_type_cd")
                               .addScalar("typeId", StandardBasicTypes.LONG)
                               .list();

ref: https://matthewbusche.com/2016/06/08/hibernate-returning-bigdecimal-instead-of-long/


Since Jpa/Hibernate by default maps the Number datatype to BigDecimal, you can not change this behavior.

You can handle the conversion in the service methods you have. Convert BigDecimal to int/long based on what the business case needs using bigDecimal.intValue() or bigDeciml.intValueExact() or bigDecimal.longValue()

0

精彩评论

暂无评论...
验证码 换一张
取 消