haju
haju

Reputation: 1298

Hibernate - BigDecimal Mapping Precision

Problem: Seems my mapping class for a big decimal is dropping 0 when grabbing values like 50.20 from the oracle database. It will grab the value correctly if its 50.23 but nothing with a 0 on the end. I imagine its something simple i am missing. Suggestions? Thanks in advance.

Details

Database: Oracle 11G Field Definition: Numeric(8,2)

mapping getter/setter

    @Column ( name="PRICE", precision = 8, scale = 2 )
private BigDecimal price;

public BigDecimal getPrice()
{
    return price;
}
public void setPrice( BigDecimal price )
{
    this.price = price;
}

Upvotes: 8

Views: 29339

Answers (3)

Khalid Hossain
Khalid Hossain

Reputation: 53

In Business Logic class you can set value in this way also:

object_name.setPrice(new BigDecimal(50.20));

Upvotes: -5

DuncanKinnear
DuncanKinnear

Reputation: 4643

I can tell you that the creation of the BigDecimal value coming back from the database is done by the proprietary JDBC driver's implementation of the getBigDecimal method of the database-specific ResultSet sub-class.

I found this out by stepping thru the Hibernate source code with a debugger, while trying to find the answer to my own question.

It seems that some implementations of the getBigDecimal method will either use the precision/scale defined in the database schema, or will try to optimise the BigDecimal returned by only defining the minimum precision/scale required to hold the value retrieved. I'm guessing that the Oracle driver is doing the latter.

See also this other question.

Upvotes: 4

Bozho
Bozho

Reputation: 597046

50.2 is the same as 50.20, 50.200, etc. If you want to display it with two digits use java.text.DecimalFormat.format(..)

Specifying precision limits the maximum number of decimal digits, not the minimum.

Upvotes: 8

Related Questions