用jpa删除父异常

时间:2017-12-11 19:14:48

标签: jpa mapping entity eclipselink jpa-2.0

使用netbeans 8.1我生成了实体和jpa控制器。 我有一个父实体和一对一关系的孩子。 子实体的主键等于父键的外键:

public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }
        private struct Test123
        {
            public string test;
        }
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            Test123 test;
            test.test = "foo";
            Test(test);
        }

        private void Test(in Test123 test)
        {
            // do nothing
        }
    }

当我尝试删除我得到的父母时:

@Entity
@Table(name = "parent")
@XmlRootElement
public class Parent implements Serializable {

 private static final long serialVersionUID = 1L;
 @Id
 @GeneratedValue(strategy = GenerationType.IDENTITY)
 @Basic(optional = false)
 @Column(name = "id")
 private Integer id;
 @OneToOne(cascade = CascadeType.ALL, mappedBy = "parent")
 private Child child;

 public Parent() {
 }
    etc....
}


@Entity
@Table(name = "child")
@XmlRootElement
public class Child implements Serializable {

  private static final long serialVersionUID = 1L;
  @Id
  @Basic(optional = false)
  @Column(name = "parent_id")
  private Integer parentId;
  @JoinColumn(name = "parent_id", referencedColumnName = "id", insertable = false, updatable = false)
  @OneToOne(optional = false)
  private Parent parent;
  public Child() {
  }
  etc....
 }

为了避免这种情况,我应该首先删除孩子,但由于cascade.ALL,它应该已经自动完成。

1 个答案:

答案 0 :(得分:0)

编码Child类如下工作

@Entity
@Table(name = "child")
@XmlRootElement
public class Child implements Serializable {

  private static final long serialVersionUID = 1L;
  @Id
  @JoinColumn(name = "parent_id", referencedColumnName = "id")
  @OneToOne(optional = false)
  private Parent parent;
  ...
}

表格看起来像

create table child (parent_id integer not null,..., primary key (parent_id))
create table parent (id integer not null, ..., primary key (id))
alter table child add constraint ... foreign key (parent_id) references parent

删除父(em.remove(parent))会导致

delete from child where parent_id=?
delete from parent where id=?