Hibernate is mapping BigDecimal incorrectly

28,688

Alright, marking this as answered as per comments with the solution being this

Share:
28,688
Pete
Author by

Pete

Oh, so they have internet on computers now!

Updated on January 25, 2020

Comments

  • Pete
    Pete about 4 years

    I have two @Entitys, both with a BigDecimal field as follows:

    in one module:

    @Entity
    @Table(name = "price_range")
    public class PriceRange extends AbstractPersistable<Long> {
        @Column(name = "price", precision = 19, scale = 4)
        private BigDecimal price;
    

    and in another module:

    @Entity
    @Table(name = "invoice_position")
    public class InvoicePosition extends AbstractPersistable<Long> {
        @Column(name = "optimized_cost", precision = 19, scale = 4)
        private BigDecimal optimizedCost;
    

    both create tables in my database with the correct precision and scale values:

    Table invoice_position
    ======================
    id,optimized_cost, ...
    ----------------------
    optimized_cost   decimal(19,4)
    

    and

    Table price_range
    =================
    id, price, ...
    -----------------
    price            decimal(19,4)
    

    A Test Frontend saves the values correctly to the database.

    However in a unit test, one of the two returns a value with a rounding error:

    0.520000000000000017763568394002504646778106689453125
    

    (debugger says: sacle = 51 and precision = 0)

    while the other is working fine:

    0.5200
    

    (debugger says: scale = 4, precision = 4)

    Both values are retrieved from the database in the same way (with an EntityManager building a CriteriaQuery with a CriteriaBuilder inside a JpaRepository):

    List<Invoice> invoices = invoiceProvider.findAll();
    List<PriceRange> priceRanges = priceRangeProvider.findAll();
    

    What could be the problem here? Or better: Where could it go wrong, if the Entity has the correct scale and precision and the database as well?

    I'm quite at a loss here, where can I look for the error?