【发布时间】:2014-05-30 19:52:12
【问题描述】:
我不知道是什么问题以及如何解决。我有Articles 和Images,它们被多对多映射。
@Entity
@Table(name="Article")
public class Article {
@Id
@GeneratedValue
private int articleId;
private String createDate;
private int state;
@ManyToMany(cascade = CascadeType.ALL, mappedBy="articles")
private Set<Image> images = new HashSet<Image>();
//setters and getters
}
和
@Entity
@Table(name="Image")
public class Image {
@Id
@GeneratedValue
private int imageId;
private String imagePath;
@ManyToMany(cascade = CascadeType.ALL)
@JoinTable(name = "ArticleImage",
joinColumns = { @JoinColumn(name = "articleId") },
inverseJoinColumns = { @JoinColumn(name = "imageId") })
private Set<Article> articles = new HashSet<Article>();
//setters and getters
}
这些是我映射的 2 个表。我在数据库中也有一个表:ArticleImage 与 articleId 和 imageId。
在我的控制器中,当我创建article 对象和image 对象时,我可以毫无问题地保存它们,但是如果我尝试在article 中设置image,我会收到错误:
org.springframework.dao.DataIntegrityViolationException: Could not execute JDBC batch update; SQL [insert into ArticleImage (articleId, imageId) values (?, ?)]; constraint [null]; nested exception is org.hibernate.exception.ConstraintViolationException: Could not execute JDBC batch update
Caused by: org.hibernate.exception.ConstraintViolationException: Could not execute JDBC batch update
Caused by: java.sql.BatchUpdateException: Cannot add or update a child row: a foreign key constraint fails (`appdatabase`.`articleimage`, CONSTRAINT `fk_ArticleImage_Article1` FOREIGN KEY (`articleId`) REFERENCES `article` (`articleId`) ON DELETE NO ACTION ON UPDATE NO ACTION)
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Cannot add or update a child row: a foreign key constraint fails (`appdatabase`.`articleimage`, CONSTRAINT `fk_ArticleImage_Article1` FOREIGN KEY (`articleId`) REFERENCES `article` (`articleId`) ON DELETE NO ACTION ON UPDATE NO ACTION)
我尝试设置所有内容并保存到数据库,但出现错误。我还尝试将article 和image 保存到数据库中(没有在图像中设置文章并且它正在工作)。然后在image 中设置article,然后更新image,但出现错误。
我应该如何处理?
编辑:
Article article = new Article();
article.setCreateDate(dateFormat.format(date));
article.setState(1);
articleService.create(article);
Image img = new Image();
img.setImagePath(path);
imageService.create(img);
Set<Article> articles = new HashSet<Article>();
articles.add(article);
img.setArticles(articles);
imageService.update(img);
我还尝试设置所有内容然后创建它们。
我的道是这样的:
public void create(Article article) {
session().save(article);
}
【问题讨论】:
-
你可能不希望两端都有
cascade = CascadeType.ALL,但我认为这不是你当前的问题,所以我不会称之为答案。 -
你能显示你当前尝试建立连接的代码吗?
-
恕我直言,您应该从两个类中删除 Set 初始化。让 Hibernate 来做。
-
@DonRoby 我在 spring mvc 中有这个,应用程序的其余部分工作正常,所以与数据库的连接正在工作..
-
@j3ny4 好的,我会这样做,但我认为它不会解决我的问题..
标签: java spring hibernate jakarta-ee