@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
}
I declared a class LoanDetails and a field with BigDecimal type loanAmount in it Whenever i saved some data in this collection
I tried to add annotation over loanAmount field
@Field(targetType = Decimal128) // This also throws error does not contain targetType attribute attached screenshot for the same
BigDecimal loanAmount
Probably, you need to drop / migrate your already created loanDetails, since the loanAmount field is persisted as String.
By adding @Field(targetType = FieldType.DECIMAL128) to your loanAmount field it should work.
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
If you get Conversion to Decimal128 would require inexact rounding of XXX
Note: The
Decimal128type 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. useBigDecimal.setScale()) method.