尝试从父实体java类中删除记录

时间:2015-09-29 21:19:56

标签: java spring hibernate jpa hsqldb

我有两个实体java类。现在我正在尝试从父实体中删除记录,但它抛出了一个错误:org.hsqldb.HsqlException: integrity constraint violation: foreign key no action; SYS_FK_10142 table: CHILD

**Parent class**
@Entity
@Table(name = "Parent")
public class Parent
{
  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  private Long id;
  @NotBlank
  @Column(name = "data")
  private String data;
  public Long getId()
  {
    return id;
  }
  public void setId(Long id)
  {
    this.id = id;
  }

  public String getData()
  {
    return data;
  }

  public void setData(String data)
  {
    this.data = data;
  }
}

**Child class**

@Entity
@Table(name = "Child")
public class Child
{
  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  private Long id;

  @NotBlank
  private String model;

  @ManyToOne()
  @OnDelete(action= org.hibernate.annotations.OnDeleteAction.CASCADE)
  private Parent parent;

  public Long getId()
  {
    return id;
  }

  public void setId(Long id)
  {
    this.id = id;
  }

  public String getModel()
  {
    return model;
  }

  public void setModel(String model)
  {
    this.model = model;
  }
}

1 个答案:

答案 0 :(得分:0)

由于您正在删除父记录并期望删除相关的子记录,因此您可能需要双向关系。

@Entity
@Table(name = "Parent")
public class Parent
{
   ...
   ...
   @OneToMany(mappedBy = "parent", cascade = javax.persistence.CascadeType.REMOVE)
   private List<Child> children;

}

@Entity
@Table(name = "Child")
public class Child
{
   ...
   ...
   @ManyToOne
   @JoinColumn(name="parent_id", referencedColumnName="id")
   private Parent parent;


}