skip to Main Content

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 (i.e 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!

2

Answers


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

    Login or Signup to reply.
  2. 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;
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search