問題描述
我們正在使用 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.
請注意,使用 double 來初始化 BigDecimal 有點奇怪.如果您希望將 1.2
存儲在 BigDecimal 中,請使用 new BigDecimal("1.2")
,您將不會使用 1.19999999999999999555910790149937383830547332763671875
初始化 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 轉換的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!