[英]How can I get spring data to save a "getter" as a mongodb field?
Question:题:
Context:语境:
averageFare
field and populates it with result getAverageFare()averageFare
字段并用结果 getAverageFare() 填充它I've tried @Field annotation我试过@Field注解
@Field("averageFare")
public BigDecimal getAverageFare() {
return fareTotal.divide(BigDecimal.valueOf(getCount()), RoundingMode.HALF_EVEN);
}
Thanks in advance!提前致谢!
You're supposed to store data, not methods.您应该存储数据,而不是方法。 You can run that calculation in the layer above.
您可以在上面的层中运行该计算。 The entity class is supposed to be a POJO and the annotation
@Field("averageFare")
can be added on the field itself rather than on the method.实体 class 应该是一个 POJO,注释
@Field("averageFare")
可以添加到字段本身而不是方法上。 You can have the method you show as a utility method which would always get you the average on the fly
rather than store it in the db.您可以将显示的方法作为一种实用方法,它总是可以让您
on the fly
而不是将其存储在数据库中。 If you need it stored, just add the averageFare
instance type field and in the setter you can perform that calculation - then you don't need the getter calculations anymore.如果您需要存储它,只需添加
averageFare
实例类型字段,然后在 setter 中您可以执行该计算 - 然后您不再需要 getter 计算。
Move the calculation logic from getter to setter.将计算逻辑从 getter 移到 setter。 It assures the field has its value as intended and the repository operates with the calculated data.
它确保该字段具有预期的值,并且存储库使用计算的数据进行操作。
@Field("averageFare")
String averageFare;
public void setAverageFare(BigDecimal averageFare) {
if (averageFare == null || this.averageFare == null || this.fareTotal == null) {
// set if the calculation would fail on NPE
this.averageFare = averageFare;
} else {
// otherwise perform the calculation
this.averageFare = this.fareTotal.divide(
BigDecimal.valueOf(getCount()),
RoundingMode.HALF_EVEN);
}
}
public BigDecimal getAverageFare() {
return averageFare;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.