1

Как мне удалить таблицу reports так, чтобы из records.report_id удалился id? Ну, то есть, удалить report так чтобы не удалялись связанные таблицы.

@Entity
@Table(name = "reports")
public class Report {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int id;

    @OneToMany(mappedBy = "report")
    private List<Record> records;
    



@Entity
@Table(name = "records")
public class Record {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int id;

    @ManyToOne
    private Report report;

Сейчас, как бы, когда я делаю:

private final ReportRepo reportRepo;

reportRepo.deleteAll();

То получаю ошибку:

2021-08-06 15:21:01.967  INFO 26287 --- [on(1)-127.0.0.1] 

o.s.web.servlet.DispatcherServlet        : Completed initialization in 5 ms
2021-08-06 15:21:09.381  WARN 26287 --- [nio-5000-exec-2] o.h.engine.jdbc.spi.SqlExceptionHelper   : SQL Error: 0, SQLState: 23503
2021-08-06 15:21:09.381 ERROR 26287 --- [nio-5000-exec-2] o.h.engine.jdbc.spi.SqlExceptionHelper   : ERROR: update or delete on table "reports" violates foreign key constraint "fknsdciwyfwp2ermy0q8wqcoh41" on table "records"
  Подробности: Key (id)=(2122) is still referenced from table "records".
2021-08-06 15:21:09.384  INFO 26287 --- [nio-5000-exec-2] o.h.e.j.b.internal.AbstractBatchImpl     : HHH000010: On release of batch it still contained JDBC statements
2021-08-06 15:21:09.574 ERROR 26287 --- [nio-5000-exec-2] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.dao.DataIntegrityViolationException: could not execute statement; SQL [n/a]; constraint [fknsdciwyfwp2ermy0q8wqcoh41]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement] with root cause

org.postgresql.util.PSQLException: ERROR: update or delete on table "reports" violates foreign key constraint "fknsdciwyfwp2ermy0q8wqcoh41" on table "records"
  Подробности: Key (id)=(2122) is still referenced from table "records".
1
  • у связи OneToMany смотри CascadeType
    – Saintka
    6 авг 2021 в 11:28

1 ответ 1

0

Единственный вариант, который я нашел - это делать всё вручную:

В модели

@Entity
@Table(name = "records")
public class Record {
  @Id
  @GeneratedValue(strategy = GenerationType.AUTO)
  private int id;

  @ManyToOne(fetch = FetchType.LAZY, targetEntity = Report.class)
  @JoinColumn(name = "report")
  private Report report;

В контроллере

    new ArrayList<Record>((Collection<? extends Record>) recordRepo.findAll()).forEach(record -> record.setReport(null));
    reportRepo.deleteAll();

Перед удалением главной таблицы обнулить id везде, где я хочу.

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.