【发布时间】:2017-11-28 23:00:12
【问题描述】:
我从 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() {
}
最后我创建了一个方法,我试图在 cascade 中 delete,将 athletes 类型的对象传递给它并删除所有相关的奖牌。
删除方法
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();
}
我遇到了约束违规:无法删除或更新父行:外键约束失败,有没有办法删除与班级运动员关联的所有对象?
谢谢大家!
【问题讨论】: