@Cascade删除不起作用(JPA,Hibernate和Spring mvc)

问题描述 投票:1回答:1

我阅读了很多关于这个主题的帖子和指南,但我仍然无法使其发挥作用。

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

为了让你更容易理解,我创建了一个简单的代码,正如你所看到的,我从数据库中获取了一个对象Utente,我从字段autorizzazioniLista中删除了一个对象Autorizzazioni,最后我保存了对象Utente。

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

在这里,您可以看到从数据库中获取的对象Utente以及集合autorizzazioniLista中的内容(有2个autorizzazioni:id 8和id 92)。 enter image description here

在这里,您可以看到,当保存对象Utente时,将从集合autorizzazioniLista中删除对象Autorizzazioni(id 8)。 enter image description here

这是用户

@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;
}

这是权限:

@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;
}

这是授权

@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;
}

有人能发现错误吗?

java hibernate spring-mvc jpa cascade
1个回答
1
投票

如果您使用相同的hibernate Session来加载对象并通过删除元素来更新集合,则需要通过将父对象引用设置为null来将依赖集合实体与其“所有者”分离。一些事情:

Autorizzazioni autorizzazioni = utente.getAutorizzazioniLista().remove(0);
autorizzazioni.setUtente(null);
session.saveOrUpdate(utente);
© www.soinside.com 2019 - 2024. All rights reserved.