简体   繁体   中英

Persist a getter value in a Spring Data Mongodb Document

I have a Model class containing a getter method I wrote and I would like to persist and retrieve that value on MongoDB. How can I accomplish that?

Suppose I have the following class, I would like to persist object1 and internalValue , even though internalValue is not a class attribute.

    @Document
    public class C {
        private SomeObj object1;
    
        public int getInternalValue() {
            return object1.doSomething();
            // Or, I could retrieve something totally unrelated
            // return 42;
        }
    }

You should have the following procedure to do it:

  1. Create a service.
  2. Create getInternalValue method in service.
  3. Create a Repository corresponding to your document C.
  4. In Service autowire Repository and save value in any specific document field.

The question is a bit old but i happen to be looking for the answer for this problem to, so here's the solution i came out with.

Simply add the AccessType annotation with property, this way a field called internalValue will also be persisted and it can also be used for search operations.

@Document
public class C {
    private SomeObj object1;

    @AccessType(PROPERTY)
    public int getInternalValue() {
        return object1.doSomething();
        // Or, I could retrieve something totally unrelated
        // return 42;
    }
}

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