我不知道问题是什么以及如何解决这个问题。我有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
对象时,我可以毫无问题地保存它们,但如果我尝试在image
中设置article
,我会得到一个错误:
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
保存到数据库中(不在图片中设置文章并且它正常工作)。然后在article
中设置image
,然后更新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);
}
答案 0 :(得分:0)
似乎问题不在代码中。它在我的数据库中。我在Article
和Image
中有一些条目,我认为这就是我收到错误的原因。我所做的只是再次从工作台创建我的数据库,我的表中没有条目,现在它正在工作:)。