我正在尝试使用Spring
&amp ;;基于某些输入进行添加。将其保存在Mongo
数据库中。
因为我必须做多次补充:
1.一种方法是手动添加值并在bean中设置它们并将其保存到数据库中。
OR
2.只需将它们添加到野外吸气器中在需要时获取。
尝试使用第二种方法时,我无法将数据保存在MongoDB中
请查找示例代码: -
Bean类:
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;
}
}
扩展MongoRepository的接口:
@Repository
public interface AdditionRepository extends MongoRepository<Addition, String> {
}
致电班级:
@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);
}
}
Mongo DB中保存的数据:
{
"_id" : ObjectId("581b229bbcf8c006a0eda4b2"),
"a" : 1.0,
"b" : 2.0,
"c" : 0.0,
"d" : 0.0,
}
任何人都可以告诉我,我做错了,或者其他任何方式。
答案 0 :(得分:1)
吸气剂实际上并不用于持久性。该框架正在使用该字段: “对象的字段用于转换文档中的字段和从文档中的字段转换” http://docs.spring.io/spring-data/mongodb/docs/1.6.3.RELEASE/reference/html/#mapping-conventions
在您的情况下,您可以创建一个构造函数来处理计算:
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;
}
}