[英]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. 我正在尝试使用
Spring
根据某些输入进行加法并将其保存在Mongo
数据库中。
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. 1.所以一种方法是手动添加值并将其设置在bean中,然后将其保存到数据库中。
OR 要么
2.Just add them in getter of field & fetch when required. 2.只需将它们添加到字段的getter中,并在需要时提取。
When tried with second approach, I am not able to save the data in MongoDB 当尝试第二种方法时,我无法将数据保存在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 : 扩展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 : 数据保存在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. 任何人都可以让我知道我做错了什么吗,或以其他任何方式做到这一点。
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
该框架改用字段:“对象的字段用于在文档中的字段之间来回转换” http://docs.spring.io/spring-data/mongodb/docs/1.6.3.RELEASE/参考/ 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;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.