使用JPA批注自动从父项和父项中删除子项 [英] Delete child from parent and parent from child automatically with JPA annotations

查看:131
本文介绍了使用JPA批注自动从父项和父项中删除子项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们有3个实体对象类:

  class Parent {
String name;
列表< Child>儿童;
}

class儿童{
字符串名称;
父母;
}

类玩具{
字符串名称;
小孩;



$ b $ p
$ b

如何使用JPA2.x(或hibernate)注释:


  1. 当父母删除(一对多)时自动删除所有孩子

  2. 它被删除(多对一)

  3. 删除玩具时自动删除(一对一)

我使用Hibernate 4.3.5和mysql 5.1.30。

谢谢

解决方案

正如中所述这篇文章删除 实体状态转换应该从父级到子级级联,而不是其他方式。



您需要类似这:

 类父母{
字符串名称;
@OneToMany(mappedBy =parent,fetch = FetchType.LAZY,cascade = CascadeType.ALL,orphanRemoval = true)
List< Child>儿童;

public void addChild(Child child){
child.setParent(this);
children.add(child);
}

public void removeChild(Child child){
children.remove(child);
if(child!= null){
child.setParent(null);
}
}
}

class儿童{
字符串名称;
@ManyToOne
父母;

@OneToOne(mappedBy =child,cascade = CascadeType.ALL,orphanRemoval = true)
玩具玩具;
}

类玩具{
字符串名称;

@OneToOne
小孩;
}


Suppose that we have 3 Entities object class:

class Parent {
    String name;
    List<Child> children;
}

class Child {
    String name;
    Parent parent;
}

class Toy {
    String name;
    Child child;
}

How can I use JPA2.x (or hibernate) annotations to:

  1. Delete all children automatically when parent delete (one to many)
  2. Delete child automatically from children list when it is deleted (many to one)
  3. Delete toy automatically when child remove (one to one)

I'm using Hibernate 4.3.5 and mysql 5.1.30.

Thanks

解决方案

As explained in this article, the remove entity state transition should cascade from parent to children, not the other way around.

You need something like this:

class Parent {
    String name;
    @OneToMany(mappedBy = "parent", fetch = FetchType.LAZY, cascade = CascadeType.ALL, orphanRemoval = true)
    List<Child> children;

    public void addChild(Child child) {
        child.setParent(this);
        children.add(child);
    }

    public void removeChild(Child child) {
        children.remove(child);
        if (child != null) {
            child.setParent(null);
        }
    }
}

class Child {
    String name;
    @ManyToOne
    Parent parent;

    @OneToOne(mappedBy = "child", cascade = CascadeType.ALL, orphanRemoval = true)
    Toy toy;
}

class Toy {
    String name;

    @OneToOne
    Child child;
}

这篇关于使用JPA批注自动从父项和父项中删除子项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆