[英]One to Many relationship cascade delete hibernate
我從冬眠開始,在2個運動員獎牌類之間有一對多的關系,我想知道是否有可能刪除 運動員並逐步消除與之相關的所有獎牌?
這是他干預的課程
@Entity
@Table(name = "Deportistas")
public class Deportistas implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "codDeportista")
private int coddeportista;
@Column(name = "nombreDeportista", columnDefinition="VARCHAR(60)")
private String nombredeportista;
@Column(name = "dniDeportista", columnDefinition="CHAR(12)")
private String dnideportista;
@ManyToOne
@JoinColumn(name = "paisDeportista")
private Paises pais;
@OneToMany(mappedBy="coddeportista", fetch=FetchType.EAGER,cascade=CascadeType.ALL)
private Set<Medallas> medalladeportista;
@OneToOne(mappedBy="iddeportista", fetch=FetchType.EAGER,cascade=CascadeType.ALL)
private Licencias licenciadeportista;
public Deportistas() {
}
----------
## medals ##
@Entity
@Table(name = "Medallas")
public class Medallas implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
@Id
@ManyToOne
@JoinColumn(name = "codDeportista")
private Deportistas coddeportista;
@Id
@ManyToOne
@JoinColumn(name = "codPrueba")
private Pruebas codprueba;
@Id
@Column(name = "fechaMedalla", columnDefinition="DATE")
private Date fechamedalla;
@Column(name = "puestoDeportista", columnDefinition="CHAR(1)")
private String puestodeportista;
public Medallas() {
}
最后,我創建了一種方法,在該方法中,我試圖級聯 刪除 ,向其傳遞運動員類型的對象並刪除所有相關的獎牌 。
public static void Delete() {
sesion.beginTransaction();
Scanner sc = new Scanner(System.in);
System.out.println("ID of the athletes to delete");
int id = sc.nextInt();
Deportistas myObject = (Deportistas) sesion.load(Deportistas.class, id);
sesion.delete(myObject);
sesion.flush();
sesion.getTransaction().commit();
}
即時通訊收到約束違規:無法刪除或更新父行:外鍵約束失敗,是否有辦法也刪除所有與班級運動員相關的對象?
謝謝大家!
首先,您應該將orphanRemoval=true
添加one-to-many
注釋中。 這意味着當與其“父”實體的關系被破壞時,從屬實體將被刪除。
我認為您需要將session.delete()
方法更改為entityManager.remove()
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.