Search code examples
javahibernatebigdecimal

hibernate save of bigdecimal


I have hibernate code , which inserts Bigdecimal number into Db column of type FLOAT. It works generally. However when I try to insert a value 0.00000000009080767 and fetch the object again, I see the returned value is different.

However when I try to insert the value using SQL query directly and then fetch using hibernate load method, I see that the SOP of getAmount method prints the value correctly.

Code:

Contact contact1 = new Contact("sailesh1117777", "[email protected]", "Vietnam1", "0904277091",new BigDecimal("0.00000000009080767"));
session.persist(contact1);
session.getTransaction().commit();
session.flush();
session.close();

session = sessionFactory.openSession();
Contact contact5 = (Contact) session.load(Contact.class, new Integer(1));
System.out.println(((BigDecimal)contact5.getAmount()).toPlainString());

<class name="Contact" table="CONTACT">
    <id name="id" column="CONTACT_ID">
        <generator class="increment"/>
    </id>
    <property name="name" type="string" column="NAME"/>
    <property name="email"/>
    <property name="address"/>
    <property name="telephone"/>
       <property name="amount" type="big_decimal"/>

</class>

OUTPUT: 0.00000000008978076


Solution

  • When hibernate save an object into the database , it calls it toString method to get the value and save it. When I inspected the BigDecimal object deeply I came to know that the toString method returns exponential value and hence the value goes into the DB with a different value. For this I wrote a custom class, extending BigDecimal and override the toString method , which internally will make call to toPlanString method of BigDecimal and helps to overcome , the exponential value getting inserted will be a diferent value.