这里我有两个实体类。我使用了OneToMany和ManyToOne映射。
@Entity
@Table(name="test_user")
public class TestUser {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer user_id;
private String user_name;
@OneToMany(mappedBy = "testuser", fetch=FetchType.EAGER, cascade = CascadeType.ALL)
private Set<UserAnswer> answer = new HashSet<UserAnswer>();
public Set<UserAnswer> getAnswer() {
return answer;
}
public void setAnswer(Set<UserAnswer> answer) {
this.answer = answer;
}
public Integer getUser_id() {
return user_id;
}
public void setUser_id(Integer user_id) {
this.user_id = user_id;
}
public String getUser_name() {
return user_name;
}
public void setUser_name(String user_name) {
this.user_name = user_name;
}
}
这是我的第二个实体类
@Entity
@Table(name="user_answer")
public class UserAnswer {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer answer_id;
private String answer;
@ManyToOne
@JoinColumn(name="user_id")
private TestUser testuser;
public TestUser getTestuser() {
return testuser;
}
public void setTestuser(TestUser testuser) {
this.testuser = testuser;
}
public Integer getAnswer_id() {
return answer_id;
}
public void setAnswer_id(Integer answer_id) {
this.answer_id = answer_id;
}
public String getAnswer() {
return answer;
}
public void setAnswer(String answer) {
this.answer = answer;
}
}
当我插入用户并回答时,user_id未存储在user_answer表中。 这是我的JSON输入格式。
{
"user_name":"myname",
"answer":[
{
"answer":"myanswer"
}
]
}
当我获取数据时,我得到像这样的JSON响应,
[
{
"user_id": 52,
"user_name": "myname",
"answer": []
}
]
这是我的服务代码段
@Autowired
private TestUserRepository repo;
@Override
public TestUser addUser(TestUser user) {
return repo.save(user);
}
这是我的控制器代码段
@Autowired
private TestUserApiService service;
@RequestMapping(value = "/saveuser", produces = { "application/json" }, consumes = { "application/json" }, method = RequestMethod.POST)
public ResponseEntity<TestUser> addUser(@RequestBody TestUser user)
throws NotFoundException {
return new ResponseEntity<TestUser>(service.addUser(user),
HttpStatus.OK);
}
答案 0 :(得分:0)
你在这里的关系是双向的,这意味着关系的每一方都应该引用另一方。
您的输入格式具有TestUser,其具有UserAnswer设置,因为您在TestUser中级联您的UserAnswer,您希望保持该关系,但您的UserAnswer应该引用TestUser以完成关系。
你可以做两件事,首先你可以使你的关系单向,或者你可以提取即将到来的UserAnswer并将TestUser注入他们然后坚持TestUser