具有JPA和灵活规模的BigDecimal [英] BigDecimal with JPA and flexible scale

查看:110
本文介绍了具有JPA和灵活规模的BigDecimal的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须在JPA中映射一个BigDecimal:

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.

但是,在给定的比例下,所有值都以4的比例存储,即使该值仅需要2的比例.例如,如果我使用像这样的数字:

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

然后该值将被截断为

12.1234

即使精度也允许更高的4位数(因为允许的精度为16且使用的精度为6,所以Hibernate可以存储10位数字,甚至将这些数字用于更高的比例).

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).

是否有任何方式可以使冬眠依赖于实际比例及其精度来适应比例,而不是采用硬编码比例?如果我没有比例地映射BigDecimal:

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; 

然后,Hibernate默认为2.在JPA中,最大可用precision的依存关系中是否有类似 flexible scale 的东西?因为在内部,BigDecimal确实执行以下操作:如果未给出小数位数(这是默认值),则Java会根据可用精度调整所需的小数位数.

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.

推荐答案

在保存实体之前,您可能希望使用@PrePersist @PreUpdate注释之类的内容来修复BigDecimal比例.

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

类似的东西:

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

@Column设置为可灵活扩展到JPA(我认为这是不可能的),您的数据库也可能需要灵活,而且我认为数据库通常没有此选项.

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.

这篇关于具有JPA和灵活规模的BigDecimal的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆