繁体   English   中英

@Cascade Delete不起作用(JPA,Hibernate和Spring MVC)

[英]@Cascade Delete not working (JPA, Hibernate and Spring mvc)

我阅读了许多有关此主题的文章和指南,但仍然无法使它起作用。

我无法从数据库中删除刚刚从父实体集合中删除的子实体(当然,插入和更新操作适用于我的子集合)。

为了使您更容易理解,我创建了一个简单的代码中,你可以看到,我从数据库中获取的对象Utente,我从外地autorizzazioniLista删除对象Autorizzazioni最后我保存对象Utente。

在图片中,您可以看到对象Autorizzazioni已从集合中删除。

在这里,您可以看到对象Utente从数据库中获取的以及集合autorizzazioniLista中的内容 (有2个autorizzazioniList :id 8和id 92)。 在此处输入图片说明

在这里您可以看到,在保存对象Utente时,已从集合autorizzazioniLista中删除了对象Autorizzazioni (id 8)。 在此处输入图片说明

这是乌腾特

@Entity
@Table(name = "utente")
@Component
public class Utente implements Serializable{

    private static final long serialVersionUID = -7124540331184173742L;

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

    @Column(name = "nome")
    @Size(min = 1, max = 45)
    @Pattern(regexp="^[A-Za-z ']*$")
    @NotBlank
    private String nome;

    @Column(name = "cognome")
    @Size(min = 1, max = 45)
    @Pattern(regexp="^[A-Za-z ']*$")
    private String cognome;

    @Column(name = "email")
    @Email
    @Size(min = 1, max = 70)
    private String email;

    @OneToOne(mappedBy = "utente", cascade = CascadeType.ALL)
    @Valid
    private Autenticazione autenticazione;  

    @OneToMany(mappedBy = "utente", fetch = FetchType.EAGER,  orphanRemoval=true, cascade = CascadeType.ALL)    
    private List<Autorizzazioni> autorizzazioniLista;
}

这是Autorizzazioni

@Entity
@Table(name = "autorizzazioni")
@Component
public class Autorizzazioni implements Serializable {

    private static final long serialVersionUID = 1167361558860087705L;      

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

    @ManyToOne(targetEntity = Utente.class)
    @JoinColumn(name = "utente", referencedColumnName = "id")
    @Size(min = 1, max = 11)
    private Utente utente;

    @ManyToOne(targetEntity = Autorizzazione.class)
    @JoinColumn(name = "autorizzazione", referencedColumnName = "id")
    @Size(min = 1, max = 11)
    private Autorizzazione autorizzazione;
}

这是Autorizzazione

@Component
@Entity
@Table(name="autorizzazione")
public class Autorizzazione implements Serializable{

    private static final long serialVersionUID = -1118124214231477185L;         

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    @Column(name="id", nullable=false, updatable=false)
    private int id; 

    @Size(min = 1, max = 45)
    @NotBlank
    @Pattern(regexp="^[A-Za-z.-_ ]*$")
    @Column(name = "descrizione")
    private String descrizione;
}

有人可以发现错误吗?

如果您使用相同的休眠Session来加载对象并通过删除元素来更新集合,则需要通过将父对象引用设置为null来使从属集合实体与其“所有者”分离。 大致情况:

Autorizzazioni autorizzazioni = utente.getAutorizzazioniLista().remove(0);
autorizzazioni.setUtente(null);
session.saveOrUpdate(utente);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM