How I can to edit these tables?
I.e. I have entities Category and Post
in Post, I have:
Code:
@ManyToMany(fetch = FetchType.EAGER, cascade = { CascadeType.MERGE, CascadeType.REFRESH, CascadeType.REMOVE })
@JoinTable(name = "category_post", joinColumns = @JoinColumn(name = "categoryId"), inverseJoinColumns = @JoinColumn(name = "postId"))
private Set<Category> categories = new HashSet<>();
in Category, I have:
Code:
@ManyToMany(fetch = FetchType.EAGER, mappedBy = "categories")
private Set<Post> posts;
I want to edit categories in the table of 'category_post'
So, I try to use custom 'update' method for Post entity
Code:
@Modifying
@Query("update ru.mrchebik.model.Post post set post.title = :title, post.text = :text, post.categories = :categories where post.postId = :postId")
void updatePost(@Param("postId") long id, @Param("title") String title, @Param("text") String text, @Param("categories") Set<Category> categories);
But also I get exception. No matter what, because I realize I have no right trying to do it.
There, I try to edit categories from Post class:
Code:
@RequestMapping(value = "{id}/edit", method = POST)
public String saveEdit(@PathVariable String id,
@RequestParam String categoriesId,
@RequestParam String title,
@RequestParam String text) {
if (categoriesId.equals("")) {
Post post = postService.findPost(Long.parseLong(id));
post.getCategory().clear();
post.setTitle(title);
post.setText(text);
postService.update(post);
} else {
Post post = postService.findPost(Long.parseLong(id));
post.getCategory().clear();
for (String category : categoriesId.split(",")) {
post.getCategory().add(categoryService.findById(Long.parseLong(category)));
}
post.setTitle(title);
post.setText(text);
postService.update(post);
}
return "redirect:/blog/";
}