gpt4 book ai didi

database - 使用 @JoinTable 时出现 org.hibernate.exception.ConstraintViolationException

转载 作者:搜寻专家 更新时间:2023-10-30 23:39:10 24 4
gpt4 key购买 nike

这是我的数据库:

------------       ----------------------       ------------
| NEWS | | NEWS_IMAGE | | IMAGE |
------------ ---------------------- ------------
| id | text| | id_news | id_image | | id | URL |
------------ ---------------------- ------------
| | | |
<-<-<-<-<-<- Foreign Key Foreign Key ->->->

在对象News 中,我有一个对象ImageList。这是我的 map 系统:

@Entity
@Table(name = "news")
class News{

@Id
@GeneratedValue
@Column(name = "id")
private long id;

@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, orphanRemoval = true)
@JoinTable(name = "news_image",
joinColumns = { @JoinColumn(name = "id_news")},
inverseJoinColumns = { @JoinColumn(name = "id_image")})
private List<Image> images = new ArrayList<Image>();}

这是对象Image:

@Entity
@Table(name = "image")
public class Image {

@Id
@Column(name = "id")
@GeneratedValue
private long id;

@Column(name = "URL")
private String URL;
}

这是我删除对象图像的方式:

News news  = org.hibernate.SessionFactory.get(News.class, id);
Image image = news.getImages().get(0);
org.hibernate.SessionFactory.getCurrentSessionFactory().delete(image);

当我尝试从表 image 中删除图像时,出现此错误:

Could not execute JDBC batch update;
SQL [delete from image where id=?];
constraint [null]; nested exception is org.hibernate.exception.ConstraintViolationException:
Could not execute JDBC batch update.

如果我删除表news_image 到表image 的外键,一切正常; Hibernate 能够先删除表news_image 中的记录,然后再删除表image 中的记录。我应该怎么办?我应该删除那个外键吗?我是不是在映射时出错了,这就是我收到该错误的原因?

提前致谢。

最佳答案

就您的映射而言,Image 对与 News 的关联一无所知,因此 NEWS_IMAGE 关联表中的相应记录永远不会被 Hibernate 删除,因为它对此一无所知。

要解决此问题,您可以按以下方式更新代码:

//News is managing the association to Image and has Cascade options defined
//so we need to update and merge the News instance
News news = org.hibernate.SessionFactory.get(News.class, id);
Image image = news.getImages().get(0);
news.getImages().remove(image);
org.hibernate.SessionFactory.getCurrentSessionFactory().saveOrUpdate(news);

或者您可以更新您的映射,以便 Image 知道关联并像以前一样继续:

新闻:

@Entity
@Table(name = "news")
class News{

@Id
@GeneratedValue
@Column(name = "id")
private long id;

@OneToMany(mappedBy = "news", cascade = CascadeType.ALL, fetch = FetchType.EAGER, orphanRemoval = true)
private List<Image> images = new ArrayList<Image>();
}

图片:

@Entity
@Table(name = "image")
public class Image {

@Id
@Column(name = "id")
@GeneratedValue
private long id;

@Column(name = "URL")
private String URL;

@ManyToOne( cascade = CascadeType.DELETE)
@JoinTable(name = "news_image",
joinColumns = { @JoinColumn(name = "id_image")},
inverseJoinColumns = { @JoinColumn(name = "id_news")})
private News news;

}

关于database - 使用 @JoinTable 时出现 org.hibernate.exception.ConstraintViolationException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37302671/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com