@RequestMapping(value = "/post/{id}/comment")
public String comment(@PathVariable("id") Long id, @ModelAttribute("comment") Comment comment, Model model) throws Exception {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
Post post = postSrv.findById(id);
if (auth != null) {
String email = auth.getName();
User currentUser = userService.findByEmail(email);
if (comment.getContent() != "") {
comment.setAuthor(currentUser);
post.getCommentList().add(comment);
comSrv.create(comment);
}
}
return "redirect:/post/{id}/";
}
堆栈跟踪:
Hibernate: insert into comments (author_id, content, date) values (?,
?, ?)
Hibernate: insert into posts_comments (post_id, comment_id) values (?,
?)
2017-10-12 18:59:22.521 WARN 7714 --- [nio-8080-exec-6]
o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Error: 1452, SQLState:
23000
2017-10-12 18:59:22.521 ERROR 7714 --- [nio-8080-exec-6]
o.h.engine.jdbc.spi.SqlExceptionHelper : Cannot add or update a
child row: a foreign key constraint fails (`blog_db`.`posts_comments`,
CONSTRAINT `FKaaxivndylqts0ji75et8xo557` FOREIGN KEY (`comment_id`)
REFERENCES `comments` (`id`))
2017-10-12 18:59:22.524 INFO 7714 --- [nio-8080-exec-6]
o.h.e.j.b.internal.AbstractBatchImpl : HHH000010: On release of
batch it still contained JDBC statements
2017-10-12 18:59:22.535 ERROR 7714 --- [nio-8080-exec-6] o.a.c.c.C.[.
[.[/].[dispatcherServlet] : Servlet.service() for servlet
[dispatcherServlet] in context with path [] threw exception [Request
processing failed; nested exception is
org.springframework.dao.DataIntegrityViolationException: could not
execute statement; SQL [n/a]; constraint [null]; nested exception is
org.hibernate.exception.ConstraintViolationException: could not
execute statement] with root cause
com.mysql.jdbc.exceptions.jdbc4.
MySQLIntegrityConstraintViolationException: Cannot add or update a
child row: a foreign key constraint fails (`blog_db`.`posts_comments`,
CONSTRAINT `FKaaxivndylqts0ji75et8xo557` FOREIGN KEY (`comment_id`)
REFERENCES `comments` (`id`))
commentList:
@OneToMany
@JoinTable(name = "posts_comments", joinColumns = @JoinColumn(name =
"post_id"),
inverseJoinColumns = @JoinColumn(name = "comment_id"))
private List<Comment> commentList;
整个项目: https://github.com/ashofthephoenix/Blog/tree/master/src/main/java/com/paulthemenace/blog
有谁知道如何解决这个问题?我在保持&#39; comment&#39;之后尝试添加到commentList,但它没有将值插入posts_comments表。删除外键不会更新comment_id值..
谢谢!