简体   繁体   中英

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?

Context:

  • The Score java object has a 'getAverageFare()' method that performs calculations
  • Another object (ie which implements @Document) has Score as a field
  • The goal: spring data, when it saves the Parent document adds an averageFare field and populates it with result getAverageFare()

I've tried @Field annotation

@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. 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. 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.

Move the calculation logic from getter to 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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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