JPA自动BigDecimal转换 [英] JPA automatic BigDecimal conversion
问题描述
我们正在使用MyEclipse生成jpa访问层.之后,我们将生成模型和数据层访问服务.对于某些领域,我们在定义精度时遇到了一些问题.
We are generating our jpa access layers with MyEclipse. Afterwards we have the generated models and data layer access services. We ran into some problems for some fields with a defined precision.
实体:
@Entity
public class TestEntity{
@Column(name="DECTEST", scale = 3, precision = 13)
BigDecimal decTest;
}
现在,我们创建一个bean并尝试保存它:
Now we create a bean and try to save it:
TestEntity te = new TestEntity();
te.setDecTest(new BigDecimal(1.2));
TestEntityService.save(te);
我们收到以下错误: 引起原因:com.ibm.db2.jcc.c.SqlException:[ibm] [db2] [jcc] [t4] [1037] [11190]在BigDecimal转换期间发生了异常.有关详细信息,请参见随附的Throwable.
We get the following error: Caused by: com.ibm.db2.jcc.c.SqlException: [ibm][db2][jcc][t4][1037][11190] Exception occurred during BigDecimal conversion. See attached Throwable for details.
Caused by: com.ibm.db2.jcc.a.a: [ibm][db2][jcc][converters][608][10994] Overflow occurred during numeric data type conversion of "1.1999999999999999555910790149937383830547332763671875".
at com.ibm.db2.jcc.a.e.a(e.java:61)
at com.ibm.db2.jcc.b.jb.a(jb.java:1772)
... 73 more
问题似乎是我们的BigDecimals比例比数据库中的比例高.
The problem seems to be that our BigDecimals scale is higher then the one from the database.
一种可行的解决方法是:
A working workaround is:
TestEntity te = new TestEntity();
BigDecimal decTest = new BigDecimal(1.2);
te.setDecTest(decTest.setScale(3,RoundingMode.HALF_UP);
TestEntityService.save(te);
通过这种解决方法,我们将BigDecimals精度手动降低为数据库之一.
With this workaround we reduce the BigDecimals precicsion manually to the one of the database.
但是,如果数据模型发生更改,我们将不得不手动调整比例.有没有办法让我们的jpa/hibernate实现为我们自动进行转换?例如.与设置属性.无论如何,在一个正在创建bean的位置执行该操作将是错误的操作.
However if the data model changes we would have to adjust the scale there manually. Is there a way to get our jpa / hibernate implementation to do that conversion for us automatically? E.g. with setting a property. Doing it at the spot where one is creating the bean would be the wrong spot to do it anyways.
推荐答案
您可以使用自定义用户类型,也可以像这样简单地实现属性的setter:
You could use a custom user type, or you could simply implement the setter of the property like this:
public void setDecTest(BigDecimal decTest) {
this.decTest = decTest.setScale(3, RoundingMode.HALF_UP));
}
因此,此舍入将封装在实体中.
This rounding would thus be encapsulated in the entity.
请注意,使用双精度型初始化BigDecimal有点奇怪.如果要将1.2
存储在BigDecimal中,请使用new BigDecimal("1.2")
,并且不会使用1.1999999999999999555910790149937383830547332763671875
初始化BigDecimal.
Note that using a double to initialize a BigDecimal is a bit strange. If you want 1.2
to be stored in the BigDecimal, use new BigDecimal("1.2")
, and you won't have a BigDecimal initialized with 1.1999999999999999555910790149937383830547332763671875
.
这篇关于JPA自动BigDecimal转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!