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
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 averageon the fly
rather than store it in the db. If you need it stored, just add theaverageFare
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.