Spring Data JPA:删除时违反外键约束

问题描述 投票:0回答:1

我有一个与

Company
实体相关的
User
实体,并且
Users
链接到一个或多个
LeaveDay
实体。当我尝试删除
Company
实体时,收到以下错误消息:

错误7300 --- [leave_tracker_postg] [nio-8080-exec-2] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] 在路径 [] 的上下文中抛出异常 [请求处理失败: org.springframework.dao.DataIntegrityViolationException:不能 执行语句[错误:更新或删除表“公司” 违反表上的外键约束“fkin8gn4o1hpiwe6qe4ey7ykwq7” “users”详细信息:键 (id)=(1) 仍从表中引用 “用户”。] [从 id=? 的公司中删除]; SQL [删除自 id=?的公司];约束 [fkin8gn4o1hpiwe6qe4ey7ykwq7]] 与 根本原因

我正在尝试删除

Company
实体并删除所有相关数据,例如
User
LeaveDay
记录。以下是我的应用程序中的实体和关系:

公司实体:

@Data
@Entity
@Table(name = "companies")
@EntityListeners(AuditingEntityListener.class)
public class Company {

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE)
    private Long id;

    @NotEmpty
    private String companyName;

    @NotEmpty
    private String country;

    private String state;

    private String zip;

    @NotEmpty
    private String address;

    private String phone;

    @Enumerated(EnumType.ORDINAL)
    private PackageType packageType;

    @OneToMany(mappedBy = "company", cascade = CascadeType.ALL, orphanRemoval = true)
    @JsonManagedReference
    private Set<User> users = new HashSet<>();

    @CreatedDate
    @Column(updatable = false)
    private LocalDateTime createdTimeStamp;

    @LastModifiedDate
    @Column(insertable = false)
    private LocalDateTime updatedTimeStamp;
}

用户实体:

@Data
@Entity
@Table(name = "users")
@EntityListeners(AuditingEntityListener.class)
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE)
    private Long id;

    @Column(nullable = false)
    private String email;

    @Column(nullable = false)
    private String password;

    @Column(nullable = false)
    private String firstName;

    @Column(nullable = false)
    private String lastName;

    private String middleName;

    private String position;

    @ManyToMany(fetch = FetchType.EAGER)
    @Enumerated(EnumType.STRING)
    private Set<Role> roles = new HashSet<>();

    private Date birthDate;

    @ManyToOne
    @JoinColumn(name = "company_id", nullable = false)
    @JsonBackReference
    private Company company;

    @OneToMany(mappedBy = "user", cascade = CascadeType.ALL, orphanRemoval = true)
    @JsonManagedReference
    private Set<LeaveDay> leaveDays = new LinkedHashSet<>();

    @ManyToMany(cascade = CascadeType.ALL)
    @JoinTable(
            name = "user_approvers",
            joinColumns = @JoinColumn(name = "user_id"),
            inverseJoinColumns = @JoinColumn(name = "approver_id")
    )
    private Set<User> approvers = new HashSet<>();

    @CreatedDate
    @Column(updatable = false, nullable = false)
    private LocalDateTime createdTimeStamp;

    @LastModifiedDate
    @Column(insertable = false)
    private LocalDateTime updatedTimeStamp;
}

LeaveDay 实体:

@Data
@Entity
@Table(name = "leave_days")
@EntityListeners(AuditingEntityListener.class)
public class LeaveDay {

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE)
    private Long id;

    @Column(nullable = false)
    private LocalDate date;

    @ManyToOne
    @JoinColumn(name = "user_id", nullable = false)
    @JsonBackReference
    private User user;

    @ManyToOne
    @JoinColumn(name = "approved_by_user_id")
    private User approvedBy;

    private String comment;

    @Enumerated(EnumType.ORDINAL)
    @Column(nullable = false)
    private LeaveDayType leaveDayType;

    @Enumerated(EnumType.ORDINAL)
    @Column(nullable = false)
    private LeaveDayStatus leaveDayStatus = LeaveDayStatus.PENDING;

    @CreatedDate
    @Column(name = "created_timestamp", updatable = false, nullable = false)
    private LocalDateTime createdTimeStamp;

    @LastModifiedDate
    @Column(name = "updated_timestamp", insertable = false)
    private LocalDateTime updatedTimeStamp;
}

确保删除

Company
时,关联的
User
记录及其
LeaveDay
记录也被删除的最佳方法是什么? 我尝试过使用
CascadeType.ALL
并在关系上设置
orphanRemoval = true
,但问题仍然存在。删除
Company
时如何确保相关记录被正确删除?

java spring-boot spring-data-jpa spring-data
1个回答
0
投票

使用

@OneToMany(mappedBy = "company")
创建单向映射,(我认为)是你的问题。

尝试切换关系,使

Company
成为“所有者”,并且
User
在关系中拥有
mappedBy
,看看是否可以解决问题。

如果您愿意,您也可以进行双向 - 请参阅此处:

JPA JoinColumn 与mappedBy

© www.soinside.com 2019 - 2024. All rights reserved.