更新时休眠多对多ConstraintViolationException

时间:2015-05-29 23:13:34

标签: mysql hibernate

我在Photo和Auteur实体之间有多对多关联,还有3个表--AUTEUR,PHOTO_AUTEUR和PHOTO。

我的Auteur映射类:

@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>();
...
}

和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;

...}

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

1 个答案:

答案 0 :(得分:0)

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

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

在Photo中使用这样的映射:

@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<>();

和Auteur:

@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<>();