gpt4 book ai didi

java - BigDecimal 存储在 spring data MongoDB 中的字符串中

转载 作者:行者123 更新时间:2023-12-05 05:50:40 24 4
gpt4 key购买 nike

@Document(collection = "loanDetails")
class LoanDetails {
@Transient
public static final String COLLECTION_NAME = "loanDetails
@Id
String id

String loanId
String loanUUID
String loanStatus
Date loanDateCreated
Date loanLastUpdated
BigDecimal loanAmount //Stores in String
}

我在其中声明了一个 LoanDetails 类和一个 BigDecimal 类型 loanAmount 的字段每当我在此集合中保存一些数据时

  1. 它在 mongo 数据库中以字符串形式存储
  2. 从数据库获取记录时出现以下错误无法解码“LoandDetails”。解码“loanAmount”错误:readDecimal只有在CurrentBSONType为DECIMAL128时才能调用,不是当 CurrentBSONType 是 STRING 时。

我尝试在 loanAmount 字段上添加注释

@Field(targetType = Decimal128) // This also throws error does not contain targetType attribute attached screenshot for the same
BigDecimal loanAmount

enter image description here

最佳答案

您可能需要删除/迁移已创建的 loanDetails,因为 loanAmount 字段作为 String 保留。

通过将 @Field(targetType = FieldType.DECIMAL128) 添加到您的 loanAmount 字段,它应该可以工作。

import org.springframework.data.mongodb.core.mapping.FieldType;
...

@Field(targetType = FieldType.DECIMAL128)
BigDecimal loanAmount;
...

public LoanDetails() {
loanAmount = new BigDecimal(21.905334472656250);
}
...

template.save(loan);

template.find(new Query(), org.bson.Document.class, "loanDetails").forEach(l -> {
System.out.println(l.get("loanAmount").getClass().getName() + " " + l.get("loanAmount"));
});
//org.bson.types.Decimal128 21.90533447265625

template.findAll(LoanDetails.class).forEach(l -> {
System.out.println(l.loanAmount.getClass().getName() + " " + l.loanAmount);
});
//java.math.BigDecimal 21.90533447265625

如果您得到 Conversion to Decimal128 would require inexact rounding of XXX

Note: The Decimal128 type only supports up to 34 digits of precision. (Generally, "precision" = total # of digits, while "scale" = # of decimal digits). Whereas a Java BigDecimal can go higher. So, before saving to the DB, you need to round the BigDecimal value (e.g. use BigDecimal.setScale()) method.

BigDecimalConverter issue | Decimal128

关于java - BigDecimal 存储在 spring data MongoDB 中的字符串中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70494158/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com