我有两个实体:A
和 B
:
在 Controller 类中我有这些方法:
@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);
}
URL /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"
}
最佳答案
您的错误是由于 Address 类的主键在保存时为空,请尝试如下操作
@RequestMapping(value="/json/add", method=RequestMethod.POST)
public @ResponseBody void addB(@RequestBody B b) {
A a = AManager.findByAddress(123456);
if(a == null)
{
// you need to create a new obj in here
a = new A();
a.setId(anyId);
//remain code
}
//then set in here
B.setA(a); // I must be from JSON, not static!
BManager.save(b);
}
对于问题 #2,请发布您的 POJO
已更新
您需要将实体 B 作为
Class B {
String id;
String name;
Address address;
//getter setters
}
Class Address
{
String address1;
String address2;
String code;
//getter setters
}
因此,在这种关系中,您需要将 json 发送为
{
name:"bla bla",
id:"12345"
address:{
address1:"any dummy address",
address2:"any dummy address",
code:"12345"
}
}
现在你的 Controller 地址对象将被 spring 自动映射到“b”对象
@RequestMapping(value="/json/add", method=RequestMethod.POST)
public @ResponseBody void addB(@RequestBody B b) {
// you can get your address object here or can save it directly
Address address = b.getAddress();
BManager.save(b);
}
关于java - Spring REST - 从 JSON 输入将实体添加到数据库 - 数据库外键错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24923418/