J
J
JackHuman2020-03-13 15:33:23
Java
JackHuman, 2020-03-13 15:33:23

How to implement cascading deletion of dependent entities (ManyToOne, OneToMany) in Hibernate?

There are entities Account and Services (abstract) in the project. Services has a child class called Deposit. Account class code:

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

Services class code:
@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;
...

Deposit additionally has an amount field, but this is not so important. When trying to delete an instance of Account, which is referenced from Deposit, it gives an error:
2020-03-13 13:29:51 ERROR SqlExceptionHelper:131 - ОШИБКА: UPDATE или DELETE в таблице "account" нарушает ограничение внешнего ключа "fk8qcea1frw0og19kft1ltq9kf9" таблицы "deposit"
Подробности: На ключ (id)=(1) всё ещё есть ссылки в таблице "deposit".

How can I set up a cascading deletion so that when an account record is deleted, the records from the deposit are automatically deleted?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
J
JackHuman, 2020-03-16
@JackHuman

In the end, the @OnDelete annotation helped. The Account class did not change. Services code:

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

A
ads83, 2020-03-14
@ads83

As far as I remember, if you specified `@ManyToOne Account` in `Services`, then you must specify `@OneToMany Services` in `Account`.
You need to register cascading settings only in one class. Here is a similar question in English .

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question