Hibernate returning BigDecimal data type, not long

A hibernate query named hibernate returns a BigDecimal for a column with data type NUMBER.

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

On the client side, I expect the col1 data type 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 suspicion is something wrong with the pseudonym?

+7
source share
5 answers

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

+5
source

I don’t know what the problem is with your hibernation configuration, but as a workaround, one trick that lets you not worry about what type of java Number Hibernate request 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 if it fits into Java long .

+4
source

Yes, Hibernate Maps Oracle Number Type for BigDecimal in Java. Since BigDecimal calculations are expensive in Java, once you get BigDecimal in Java, write a Utility to convert a BigDecimal collection to an Integer or Long collection based on your data size.

+1
source

Since Jpa / Hibernate by default maps the Number data type to BigDecimal, you cannot change this behavior.

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

0
source

I have the same problem. This solves the problem neatly and returns a list of long

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

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

0
source

Source: https://habr.com/ru/post/1344625/


All Articles