【发布时间】:2014-07-24 00:49:05
【问题描述】:
我有两个实体:A 和 B:
在控制器类中我有这些方法:
@RequestMapping(value="/json/get", method=RequestMethod.GET)
public @ResponseBody List<B> getAll() {
return BManager.findAll();
}
@RequestMapping(value="/json/add", method=RequestMethod.POST)
public @ResponseBody void addB(@RequestBody B b) {
B.setA(AManager.findByAddress(123456)); // I must be from JSON, not static!
BManager.save(b);
}
网址/json/get返回给我:
{
"value":1,
"title":"hello"
}
A 没有任何价值。但没关系。问题是当我想从 JSON 输入创建新的 B 实体时。
我发送
curl -X POST -H "Content-Type: application/json" -H "Accept: application/json" -d '{"value":2,"title":"world"}' http://localhost:8080/test/json/add
如果我在方法addB 行B.setA(AManager.findByAddress(123456)); 中将实体保存到数据库。但我需要像这样在输入 JSON 中指定地址(我可以更改 json 语法):
curl -X POST -H "Content-Type: application/json" -H "Accept: application/json" -d '{"address":123456,"value":2,"title":"world"}' http://localhost:8080/test/json/add
它崩溃了:
SEVERE: Servlet.service() for servlet [spring] in context with path [/test] threw exception [Request processing failed; nested exception is org.springframework.dao.DataIntegrityViolationException: could not execute statement; SQL [n/a]; constraint [null]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement] with root cause
com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Column 'A_id' cannot be null
问题:
1) 如何在输入 JSON 中从 B 指定地址(A 类)?
2) 如果我想要方法 getAll 的输出 JSON(B 类)中的地址(来自 A 类),我该怎么做?
我想得到/json/get:
{
"addrress":123456,
"value":1,
"title":"hello"
}
【问题讨论】:
标签: java json spring rest jackson