开发者社区> 问答> 正文

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

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

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

另外,存款中有一个金额字段,但这并不是那么重要:

@Entity
public class Deposit extends Services {
  @Column
  private double amount;

尝试删除“存款”中有链接的“帐户”实例时,出现错误:

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.

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

问题来源:Stack Overflow

展开
收起
montos 2020-03-27 12:27:25 444 0
1 条回答
写回答
取消 提交回答
  • 通常,注释@OnDelete会有所帮助。帐户类未更改。服务代码:

    @MappedSuperclass
    abstract public class Services {
      @Id
      @GeneratedValue(strategy = GenerationType.IDENTITY)
      protected long id;
      @ManyToOne(cascade = CascadeType.REFRESH)
      @JoinColumn(name = "from_account_id")
      @OnDelete(action = OnDeleteAction.CASCADE)
      protected Account fromAcc;
    ...
    

    回答来源:Stack Overflow

    2020-03-27 12:27:49
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
低代码开发师(初级)实战教程 立即下载
冬季实战营第三期:MySQL数据库进阶实战 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载