删除数据模型时违反参照完整性约束

时间:2019-05-15 06:45:09

标签: java spring jpa

我有两个数据模型-讲道和讲道会话。一个讲道会话可以包含许多讲道,而一个讲道只能有一个讲道会话:

布道

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(updatable = false, nullable = false, unique = true)
@SuppressWarnings("unused")
private int id;
@Column(unique = true)
private String fileName;
private String name;
private String speaker;
private int duration;
@ManyToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "sermon_session_id", referencedColumnName = "id")
private SermonSession sermonSession;
private LocalDate date;
private LocalDate uploadDate;
private String description;
@ElementCollection
@CollectionTable(
    name = "SERMON_DATA_TAGS",
    joinColumns = @JoinColumn(name = "id", referencedColumnName = "id"))
@Column(name = "tag")
private List<String> tags;

布道会议

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(updatable = false, nullable = false, unique = true)
@SuppressWarnings("unused")
private int id;
@Enumerated(EnumType.STRING)
@Column(unique = true)
private SessionEnum sessionEnum;

每当我尝试删除一条布道时,我都会不断收到以下错误消息:

delete from sermon_session where id=? [23503-197]]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement] with root cause

org.h2.jdbc.JdbcSQLException: Referential integrity constraint violation: "FK7WS4Y2S081JPFSURR19K9WVCR: PUBLIC.SERMON_DATA FOREIGN KEY(SERMON_SESSION_ID) REFERENCES PUBLIC.SERMON_SESSION(ID) (2)"; SQL statement:
delete from sermon_session where id=? [23503-197]

我该如何解决?我应该能够删除布道,而无需删除布道会话

更新

添加了我的删除方法:

CRUDResponse deleteSermon(int id, String host) {
    if (sermonDataRepository.findById(id).isPresent()) {
        SermonData deleteSermon = sermonDataRepository.findById(id).get();

        if (activeProfile.equals("live")) {
            awsService.deleteFileFromS3Bucket(deleteSermon.getFileName());
        }
        sermonDataRepository.delete(deleteSermon);

        return new CRUDResponse(
                deleteSermon,
                HttpStatus.OK.value(),
                String.format("%s%s/%d",
                host,
                applicationConfiguration.getRestSermonPath(),
                deleteSermon.getId()),
                Message.DELETED
        );
    } else
        return new CRUDResponse(
                null,
                HttpStatus.NOT_FOUND.value(),
                String.format("%s%s/%d", host, applicationConfiguration.getRestSermonPath(), id),
                Message.NOT_FOUND
        );
}

0 个答案:

没有答案