这是我第一次尝试编写具有双向ManyToOne
关系的实体的REST服务。代码如下,我遇到了以下问题:
当我向/ posts /运行POST请求时,它每次都会创建一个新类别,将JSON中的类别部分视为新类别的名称。
Post.java
@Entity
public class Post {
@Column(name = "post_id")
private Long id;
@Column(nullable = false, length = 255)
private String title;
@Column(nullable = false, length = 999999)
private String text;
private Category category;
// Constructors
public Post() {
}
public Post(String title, String text, Category category) {
this.title = title;
this.text = text;
this.category = category;
}
// Getters and Setters
@Id @GeneratedValue(strategy = GenerationType.IDENTITY)
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
@ManyToOne(fetch = FetchType.EAGER, cascade = CascadeType.PERSIST)
@JoinColumn(name = "category_id")
public Category getCategory() {
return category;
}
public void setCategory(Category category) {
this.category = category;
}
}
Category.java
@Entity
public class Category {
@Column(name = "category_id")
private Long id;
@Column(nullable = false)
private String name;
@Column(nullable = false)
private String slug;
private List<Post> posts;
// Constructors
public Category() {
}
public Category(String name, String slug) {
this.name = name;
this.slug = slug;
}
public Category(String name) {
this.name = name;
}
// Adding posts to existing categories
public void addPost(Post post) {
this.posts.add(post);
}
// Getters and setters
@Id @GeneratedValue(strategy = GenerationType.IDENTITY)
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSlug() {
return slug;
}
public void setSlug(String slug) {
this.slug = slug;
}
@JsonIgnore @OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, mappedBy = "category")
public List<Post> getPosts() {
return posts;
}
public void setPosts(List<Post> posts) {
this.posts = posts;
}
// toString
@Override
public String toString() {
final StringBuffer sb = new StringBuffer("Category{");
sb.append("id=").append(id);
sb.append(", name='").append(name).append('\'');
sb.append(", slug='").append(slug).append('\'');
sb.append(", posts=").append(posts);
sb.append('}');
return sb.toString();
}
}
PostController.java
@RequestMapping(value = "/posts")
@RestController
public class PostController {
@Autowired
PostRepository repository;
@RequestMapping(method = RequestMethod.GET)
public @ResponseBody List<Post> getAllPosts() {
return repository.findAll();
}
@RequestMapping(method = RequestMethod.POST)
@ResponseStatus(HttpStatus.CREATED) public
@ResponseBody Post createPost(@RequestBody Post post) {
return repository.save(post);
}
}
答案 0 :(得分:1)
public void addPost(Post post) {
this.posts.add(post);
post.setCategory(this);
}