I'm currently developing the application like a making blog service. Then, I added some functions that could edit and delete the blog. In order to add the function that could delete the blog that has comment object, I wrote the code "@OneToMany(mappedBy="blog",cascade=CascadeType.ALL,orphanRemoval=true)" then, it couldn't be editing the blog. The Error occurred. Please tell me where to modify. I'm a beginner.
Java 8
spring boot version 2.2.12
A collection with cascade="all-delete-orphan" was no longer referenced by the owning entity instance: jp.kuroda.sampleBlog.model.Blog.comments; nested exception is org.hibernate.HibernateException:
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:212)
at com.sun.proxy.$Proxy1467.save(Unknown Source)
at jp.kuroda.sampleBlog.service.BlogService.editBlog(BlogService.java:54)
at jp.kuroda.sampleBlog.controller.PersonController.editBlog(PersonController.java:100)
@Entity
@Data
public class Blog {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private Integer id;
@ManyToOne
private Person person;
@OneToMany(mappedBy="blog",cascade=CascadeType.ALL,orphanRemoval=true)
private List<Comment> comments;
}
@Entity
@Data
public class Comment {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private Integer id;
@ManyToOne
@JoinColumn(name="blog_id")
private Blog blog;
@ManyToOne
private Person person;
}
@Service
public class BlogService {
public void editBlog(Blog blog) {
blog.setPostDateTime(LocalDateTime.now()
.format(DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss")));
blogRepository.save(blog);
}
public void deleteBlog(Blog blog) {
blogRepository.deleteById(blog.getId());
}
}
@Controller
@RequestMapping("/person")
public class PersonController {
@Autowired
private PersonService personService;
@Autowired
private BlogService blogService;
@GetMapping("/blog/{blogId}/edit")
public String editBlog(@PathVariable("blogId")Blog blog,Model model) {
model.addAttribute("base64image",blog.getBase64_str());
model.addAttribute("blog",blog);
return"person/create";
}
@PostMapping("/blog/{blogId}/edit")
public String editBlog(@Valid Blog blog,BindingResult bindingResult) {
if(bindingResult.hasErrors()) {
return"person/create";
}
blogService.editBlog(blog);
return"redirect:/person/edit";
}
}