一对多关系级联删除hibernate

时间:2017-11-28 23:00:13

标签: java 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();

    }

我得到一个约束违规:无法删除或更新父行:外键约束失败,有没有办法删除所有与该类运动员相关的对象?

感谢所有人!

1 个答案:

答案 0 :(得分:0)

首先,您应该将orphanRemoval=true添加到one-to-many注释中。这意味着当与他们的父母的关系被删除时,将删除依赖实体。实体将被销毁。

我认为您需要将session.delete()方法更改为entityManager.remove()