【问题标题】:Hibernate cascade delete dependent entities (ManyToOne OneToMany)Hibernate级联删除依赖实体(ManyToOne OneToMany)
【发布时间】:2020-06-25 11:23:53
【问题描述】:

在项目中有实体帐户和服务(摘要)。服务有一个子类,存款。帐户类代码:

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

当尝试删除存在来自 Deposit 的链接的 Account 实例时,它会给出错误:

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.

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

【问题讨论】:

  • 存款实体在哪里?
  • 通过向您的 Account 实体添加 OneToMany 映射并在其上放置级联配置?
  • @Gimby,它不起作用。

标签: java hibernate jpa one-to-many hibernate-mapping


【解决方案1】:

一般来说,@OnDelete 注释很有帮助。 Account 类没有改​​变。服务代码:

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

【讨论】:

    猜你喜欢
    • 2022-12-03
    • 2014-11-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-26
    • 1970-01-01
    相关资源
    最近更新 更多