gpt4 book ai didi

mysql - 更新时出现 Hibernate 多对多 ConstraintViolationException

转载 作者:行者123 更新时间:2023-11-29 22:23:05 27 4
gpt4 key购买 nike

我在 Photo 和 Auteur 实体之间建立了多对多关联,并有 3 个表 - AUTEUR、PHOTO_AUTEUR 和 PHOTO。

我的作者映射类:

@Entity
@Table(name = "AUTEUR")
public class Auteur implements Serializable {
@Id
@GeneratedValue
@Column(name = "auteur_id")
private int auteur_id;
@Column(name = "nom")
private String nom;
@Column(name = "prenom")
private String prenom;
@ManyToMany(fetch = FetchType.EAGER, cascade = {CascadeType.ALL},
targetEntity = Photo.class)
@JoinTable(name = "PHOTO_AUTEUR",
joinColumns = {
@JoinColumn(name = "AUTEUR_ID")},
inverseJoinColumns = {
@JoinColumn(name = "PHOTO_ID")})
private Set<Photo> photos = new HashSet<Photo>();
...
}

和一个照片类:

@Entity
@Table(name = "PHOTO")
public class Photo extends News {
@Id
@GeneratedValue
@Column(name = "photo_id")
private int id;
@Column(name = "format")
private String format;
@Column(name = "largeur")
private int largeur;
@Column(name = "hauteur")
private int hauteur;
@Column(name = "siColoree")
private boolean siColoree;
@ManyToMany(mappedBy = "photos", fetch = FetchType.EAGER, cascade = CascadeType.ALL, targetEntity = Auteur.class)
private Set<Auteur> photo_auteurs = new HashSet<>();
@Lob
@Column(name = "image", length = 1000000)
private byte[] image;

...}

当我尝试更新或删除照片条目时,即使我在 mySql 中手动设置了级联删除和更新,我也会收到 ConstraintViolationException。

最佳答案

它可以正常工作,没有级联限制

SessionFactory sf = HibernateUtil.getSessionFactory();
Session session = sf.openSession();
session.beginTransaction();
session.delete(photo);
session.getTransaction().commit();
session.close();

在照片中使用这样的映射:

@ManyToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
@JoinTable(name = "PHOTO_AUTEUR",
joinColumns = @JoinColumn(name = "PHOTO_ID"),
inverseJoinColumns = @JoinColumn(name = "AUTEUR_ID"))
private Set<Auteur> photo_auteurs = new HashSet<>();

在作者中:

@ManyToMany(fetch = FetchType.EAGER, targetEntity = Photo.class)
@JoinTable(name = "PHOTO_AUTEUR",
joinColumns = {
@JoinColumn(name = "AUTEUR_ID")},
inverseJoinColumns = {
@JoinColumn(name = "PHOTO_ID")})
private Set<Photo> photos = new HashSet<>();

关于mysql - 更新时出现 Hibernate 多对多 ConstraintViolationException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30540430/

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