【问题标题】:One to Many relationship cascade delete hibernate一对多关系级联删除休眠
【发布时间】: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() {

    }

最后我创建了一个方法,我试图在 cascadedelete,将 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();

    }

我遇到了约束违规:无法删除或更新父行:外键约束失败,有没有办法删除与班级运动员关联的所有对象?

谢谢大家!

【问题讨论】:

    标签: java hibernate


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 2019-07-31
      • 1970-01-01
      • 2012-01-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-12
      • 2010-11-03
      • 1970-01-01
      相关资源
      最近更新 更多