【发布时间】:2015-11-08 21:41:11
【问题描述】:
我被一些事情困住了,经过一天的搜索和尝试不同的事情,我认输了。我有 2 个基本域,一个博客文章和一个作者。我留下了一些代码来保持这篇文章的简短。
@Entity
public class Post {
@Id @GeneratedValue
private Long id;
private String title;
@Column(columnDefinition = "TEXT")
private String body;
@Column(columnDefinition = "TEXT")
private String teaser;
private String slug;
@CreatedDate
@Temporal(TemporalType.TIMESTAMP)
private Date postedOn;
@ManyToOne
private Author author;
// getters & setters
}
@Entity
public class Author {
@Id
@GeneratedValue
private Long id;
private String firstName;
private String lastName;
private String email;
// getters & setters
}
控制器长这样
@RestController
@RequestMapping("/posts")
public class PostController {
private PostService postService;
@Autowired
public PostController(PostServiceImpl postService){
this.postService = postService;
}
@RequestMapping( value = "/", method = RequestMethod.GET )
public Iterable<Post> list(){
return postService.list();
}
@RequestMapping( value = "/", method = RequestMethod.POST )
public Post create(@RequestBody Post post){
return postService.save(post);
}
@RequestMapping( value = "/{id}", method = RequestMethod.GET )
public Post read(@PathVariable(value="id") long id){
return postService.getPost(id);
}
@RequestMapping( value = "/{id}", method = RequestMethod.PUT )
public String update(@PathVariable(value="id") int id){
return "post.update()";
}
@RequestMapping( value = "/{id}", method = RequestMethod.DELETE )
public String delete(@PathVariable(value="id") int id){
return "post.delete()";
}
}
所有服务方法所做的就是获取 Post POJO 并调用存储库上的保存方法。这是我的问题,我什至觉得问它很愚蠢。当我从没有作者(null)的 Postman 发布 JSON 时,一切正常。我只是不确定如何用新作者或现有作者发布 json 对象。
这行得通
{
"title" : "A new post created from JSON",
"slug" : "a-new-post",
"teaser" : "post teaser",
"body" : "post body",
"postedOn" : "2015-11-07"
}
当我尝试发布此 JSON 时
{
"title" : "A new post created from JSON",
"slug" : "a-new-post",
"teaser" : "post teaser",
"body" : "post body",
"postedOn" : "2015-11-07",
"author" : {
"firstName": "Joe",
"lastName": "Smith",
"email": "jsmith@gmail.com"
}
}
我收到以下错误
{
"timestamp": 1447018768572,
"status": 500,
"error": "Internal Server Error",
"exception": "org.springframework.dao.InvalidDataAccessApiUsageException",
"message": "org.hibernate.TransientPropertyValueException: object references an unsaved transient instance - save the transient instance before flushing : com.therealdanvega.domain.Post.author -> com.therealdanvega.domain.Author; nested exception is java.lang.IllegalStateException: org.hibernate.TransientPropertyValueException: object references an unsaved transient instance - save the transient instance before flushing : com.therealdanvega.domain.Post.author -> com.therealdanvega.domain.Author",
"path": "/posts/"
}
【问题讨论】: