8

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;
}
Bozho
  • 588,226
  • 146
  • 1,060
  • 1,140
haju
  • 1,278
  • 4
  • 20
  • 38
  • when I execute the hibernate .getList , it grab 50.2 and not 50.20 as it is in the database. The only thing I can think is its has to do with the mapping to the field. I also tried making it a double, made no difference. – haju Oct 13 '11 at 14:28

3 Answers3

8

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.

Bozho
  • 588,226
  • 146
  • 1,060
  • 1,140
  • 1
    Ya but why would hibernate trim it? In the database its 50.20, my mapping class shouldn't trim the trailing 0's I would think by default. – haju Oct 13 '11 at 14:26
  • 1
    This is just e presentation issue. Noone trims the zero, it is just not displayed by toString. – Bozho Oct 13 '11 at 14:32
  • You mean the toString even in the debugger? The price is mapped to a BigDecimal. In my code when I set the break point on the point where it gets that list of object values, i see the value mapped as 58.2 . No toString is called yet. I just thought by having that precision annotation on my @Column it would maintain the value. – haju Oct 13 '11 at 14:40
  • 1
    As I said, precision is about the maximum. For setting how you want to display it use a decimal format. – Bozho Oct 13 '11 at 15:02
  • The debugger uses toString to display BigDecimals. – Lluis Martinez Feb 25 '13 at 11:56
4

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.

Community
  • 1
  • 1
DuncanKinnear
  • 4,563
  • 2
  • 34
  • 65
-4

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

object_name.setPrice(new BigDecimal(50.20));