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

Trying to delete a record from a parent entity java class

我有两个实体 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;
  }
}

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

@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;


}