简体   繁体   English

如何获取 spring 数据以将“getter”保存为 mongodb 字段?

[英]How can I get spring data to save a "getter" as a mongodb field?

Question:题:

  • How can I get spring data to save a "getter" as a mongodb field?如何获取 spring 数据以将“getter”保存为 mongodb 字段?

Context:语境:

  • The Score java object has a 'getAverageFare()' method that performs calculations得分 java object 有一个执行计算的“getAverageFare()”方法
  • Another object (ie which implements @Document) has Score as a field另一个 object(即实现@Document 的)将 Score 作为字段
  • The goal: spring data, when it saves the Parent document adds an averageFare field and populates it with result getAverageFare()目标:spring 数据,当它保存父文档时添加一个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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM