nimo23
nimo23

Reputation: 5680

BigDecimal with JPA and flexible scale

I have to map a BigDecimal in JPA:

@Column(name = "price", precision = 16, scale = 4)
private BigDecimal price;

The precision and scale is also set up in the database correctly.

However, with the given scale, all values are stored with a scale of 4 even the value does only need a scale of 2. And if, for example, I use a number like:

12.12345678

then this value is truncated to

12.1234

even the precision would allow a higher scale of 4 (because the allowed precision is 16 and the used precision is 6, hence Hibernate could store 10 digits more and use these digits even for the needed higher scale).

Is there any way that hibernate adapts the scale in dependent of the actual scale and its precision instead of having hard coded scale? If I map the BigDecimal with no scale:

@Column(name = "price", precision = 16)
private BigDecimal price; 

then Hibernate defaults to 2. Is there something like a flexible scale in dependend of the maximum available precision in JPA? Because internally, BigDecimal does exactly something like that: If no scale is given (which is the default), then java adapts the needed scale in accordance to the available precision.

Upvotes: 1

Views: 7971

Answers (1)

Kosonome
Kosonome

Reputation: 470

Probably you want something like @PrePersist @PreUpdate annotations to fix your BigDecimal scale before saving your entity.

Something like:

@PrePersist
@PreUpdate
    public void pricePrecisionConvertion() {
        // convert your bigdecimal scale to 2 here
        this.price.setScale(2, RoundingMode.HALF_UP);
    }

Setting @Column to a flexible scale to JPA (which I think it's not possible), your database could need be flexible as well, and I don't think databases in general have this option.

Upvotes: 2

Related Questions