【发布时间】:2016-11-03 13:24:43
【问题描述】:
我正在尝试使用 Spring 根据某些输入进行添加并将其保存在 Mongo 数据库中。
因为我必须做多次加法:
1.So一种方法是手动添加值并将它们设置在bean中并将其保存到数据库中。
或
2.只需将它们添加到字段的getter中并在需要时获取。
当尝试使用第二种方法时,我无法将数据保存在 MongoDB 中
请查找示例代码:-
豆类:
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,
}
谁能告诉我,我在哪里做错了,或者任何其他方式。
【问题讨论】:
标签: java spring mongodb spring-mvc