Avoid problems with BigDecimal when migrating to Java 1.4 in Java 1.5+

I recently migrated a Java 1.4 application to a Java 6 environment. Unfortunately, I ran into a storage problem BigDecimalin an Oracle database. To summarize, when I try to store a "7.65E+7"BigDecimal ( 76,500,000.00) value in a database, Oracle actually stores the value 7,650,000.00. This defect is caused by class rewriting BigDecimalin Java 1.5 (see here ).

In my code BigDecimalwas created from doubleusing this type of code:

BigDecimal myBD = new BigDecimal("" + someDoubleValue);
someObject.setAmount(myBD);
// Now let Hibernate persists my object in DB...

In more than 99% of cases, everything works fine. Except in very few cases, the error mentioned above occurs. And that is pretty annoying.

If I changed the previous code to avoid using the String constructor BigDecimal, then I do not encounter an error in my use cases:

BigDecimal myBD = new BigDecimal(someDoubleValue);
someObject.setAmount(myBD);
// Now let Hibernate persists my object in DB...

However, how can I be sure that this solution is the right way to use it BigDecimal?

So my question is to know how to manage my values BigDecimalin order to avoid this problem:

  • Do not use constructor new BigDecimal(String)and use directly new BigDecimal(double)?
  • Forced to use Oracle toPlainString()instead of a method toString()when working with BigDecimal(in which case, how to do this)?
  • Any other solution?

Environment Information:

  • Java 1.6.0_14
  • Hibernate 2.1.8 (yes, this is a pretty old version)
  • Oracle JDBC 9.0.2.0 and also tested with 10.2.0.3.0
  • Oracle Database 10.2.0.3.0

: , Oracle JDBC 10.2.0. 4.0 ! 76,500,000.00... changelog, , # 4711863.

+3
2

: Hibernate, MyBigDecimal, toString() toPlainString()?

cosntructor BigDecimal - , 2 ( ). BigDecimal , .

+2

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


All Articles