休眠级联删除依赖实体(ManyToOne OneToMany)

问题描述 投票:1回答:1

在项目中,有实体帐户和服务(抽象)。服务有一个子班,定金。帐户类别代码:

@Entity
public class Account {
  private static Logger log = LogManager.getLogger(Account.class);

  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  private long id;
  @Column
  private double amount;
  @Column
  private AccountType type;
  @Column(name = "date_start")
  private Date dateStart;
  @Column(name = "date_end")
  private Date dateEnd;
  @Column(name = "in_rate")
  private short inRate;
  @ManyToOne
  @JoinColumn(name = "client_id")
  private Client client;
...

服务类代码:

@MappedSuperclass
abstract public class Services {
  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  protected long id;
  @ManyToOne(cascade=CascadeType.ALL)
  @JoinColumn(name = "from_acc_id")
  protected Account fromAcc;
...

另外,存款中有一个数量字段,但这不是很重要。尝试删除“帐户”实例(从“存款”中有链接)到该实例时,出现错误:

2020-03-13 13:29:51 ERROR SqlExceptionHelper: 131 - ERROR: UPDATE or DELETE in the "account" table violates the foreign key constraint "fk8qcea1frw0og19kft1ltq9kf9" of the "deposit" table
Details: The key (id) = (1) still has links in the "deposit" table.

如何配置级联删除,以便在删除帐户记录时自动删除存款记录?=

java hibernate jpa one-to-many hibernate-mapping
1个回答
0
投票

您将需要定义双向关系,并将更改与删除孤儿串联在一起:

@Entity
public class Account {

    // all the fields
    @OneToMany(mappedBy="account", cascade=CascadeType.ALL, orphanRemoval=true)
    protected List<Deposit> deposits;
}
© www.soinside.com 2019 - 2024. All rights reserved.