Hibernate cascade delete dependent entities (ManyToOne OneToMany)

JackHuman :

In the project there are entities Account and Services (abstract). Services has a child class, 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 in addition has an amount field, but this is not so important:

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

When trying to delete an instance of Account, to which there are links from Deposit, it gives an error:

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.

How to configure delete on cascade so that when deleting an account record, records from deposit are deleted automatically?

JackHuman :

In general, the annotation @OnDelete 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;
...

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=291492&siteId=1
Recommended