Devang Thakkar
Devang Thakkar

Reputation: 51

Not able to save value In Mongo DB from Spring using MongoRepository

I am trying to do addition based on certain input's using Spring & save it in Mongo database.

As I have to do multiple addition :

1.So one way is to manually add the values and set them in bean and save it to the database.

OR

2.Just add them in getter of field & fetch when required.

When tried with second approach, I am not able to save the data in MongoDB

Please find sample code :-

Bean Class :

class Addition {

    private double a;
    private double b;
    private double c;
    private double d;

    //getters and setters of a & b;

    //getter of c;
    public double getC() {
        return a + b;
    }

    //getter of d;
    public double getD() {
        return getC() + a;
    }

}

Interface which extends MongoRepository :

@Repository
public interface AdditionRepository extends MongoRepository<Addition, String> {

}

Calling Class :

@Controller
public class Add {

    @Autowired
    private AdditionRepository additionRepository;

    @RequestMapping(value = "/add", method = RequestMethod.GET)
        public void addNumbers(){
            Addition addition = new Addition();
            addition.setA(1.0);
            addition.setB(2.0);
            System.out.println(addition.getC()); //able to print expected value
            System.out.println(addition.getD()); //able to print expected value

            additionRepository.save(addition);

    }

}

Data Saved in Mongo DB :

{
   "_id" : ObjectId("581b229bbcf8c006a0eda4b2"),
   "a" : 1.0,
   "b" : 2.0,
   "c" : 0.0,
   "d" : 0.0,
}

Can anybody please let me know, where I am doing wrong, Or any other way of doing this.

Upvotes: 1

Views: 1793

Answers (1)

xsenechal
xsenechal

Reputation: 359

The getters are not actually used for persistance. The framework is using the field instead: "The fields of an object are used to convert to and from fields in the document" http://docs.spring.io/spring-data/mongodb/docs/1.6.3.RELEASE/reference/html/#mapping-conventions

In your case, you could create a constructor which will take care of the computation:

class Addition {

    private double a;
    private double b;
    private double c;
    private double d;

    public Addition(double a, double b){
        this.a = a;
        this.b = b;        
        this.c = a+b;
        this.d = this.c + a;
    }
}

Upvotes: 1

Related Questions