首页 > 解决方案 > 如何使用 JPA/Hibernate 将“On Delete Cascade”添加到加入表

问题描述

我有以下实体。

这是一个优惠券购买系统。它为每个实体创建 3 个表,另一个表的名称customer_coupons通过外键保存所有客户购买

在 DB 中跟随 DDLcustomer_coupons

CREATE TABLE `customer_coupons` (
  `customer_id` int NOT NULL,
  `coupons_id` int NOT NULL,
  KEY `FK3ra7y4e2fu00kui0lby4mj0w1` (`coupons_id`),
  KEY `FK2xh7flxxfqpn6prhw5n06l4nn` (`customer_id`),
  CONSTRAINT `FK2xh7flxxfqpn6prhw5n06l4nn` FOREIGN KEY (`customer_id`) REFERENCES `customer` (`id`) ON DELETE CASCADE,
  CONSTRAINT `FK3ra7y4e2fu00kui0lby4mj0w1` FOREIGN KEY (`coupons_id`) REFERENCES `coupon` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci

公司类别:

@Entity
@AllArgsConstructor
@NoArgsConstructor
@Builder
@Data
public class Company {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;

    @Column(nullable = false, unique = true)
    private String name;

    @Column(nullable = false, unique = true)
    private String email;

    private String password;

    @Singular
    @OneToMany(cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.EAGER, mappedBy = "company")
    @OnDelete(action = OnDeleteAction.CASCADE)
    private List<Coupon> coupons;

客户类别:

@Entity
@AllArgsConstructor
@NoArgsConstructor
@Builder
@Data
public class Customer {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;

    private String firstName;
    private String lastName;

    @Column(nullable = false, unique = true)
    private String email;
    private String password;

    @Singular
    @ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
    @OnDelete(action = OnDeleteAction.CASCADE)
    private List<Coupon> coupons;

优惠券类别:

@Entity
@AllArgsConstructor
@NoArgsConstructor
@Builder
@Data
public class Coupon {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;
    
    @ManyToOne()
    @ToString.Exclude
    private Company company;

    @Enumerated(EnumType.STRING)
    private Category category;
    private String title;
    private String description;
    private Date startDate;
    private Date endDate;
    private int amount;
    private double price;
    private String image;

我会创建一个级联删除,当您在数据库中删除一家公司时,它将删除所有优惠券,并将删除所有优惠券购买。(同理,删除客户时,不会删除优惠券,而是删除join表中的购买)

所以我的问题是,如何在表上的外键中添加coupons_idon customer_coupons delete cascade 选项

标签: javamysqlspringhibernatejpa

解决方案


您可以使用@JoinTable注释为双方定义带有注释的外键@ForeignKey。在该定义中,您可以指定您的ON DELETE CASCADE选项。


推荐阅读