java - 如何使用 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_id
on customer_coupons
delete cascade 选项
解决方案
您可以使用@JoinTable
注释为双方定义带有注释的外键@ForeignKey
。在该定义中,您可以指定您的ON DELETE CASCADE
选项。
推荐阅读
- java - 如何从 Java 中的运行查询中获取 postgres 模式
- javascript - JS:将 Web 控制台消息重定向/保存到 txt 文件
- leaflet - 如何在 Leaflet 图例(或其他控件)的工具提示中使用 HTML?
- javascript - 如何使用回调对命令中的事件链进行排序?
- ios - 根据 Swift 4、Xcode 12 中的搜索条件更新 Firestore 集合中的所有文档
- r - 在评估“Rscript”缓冲区中的代码时,ESS 将焦点切换到“R”缓冲区
- azure - 如何将 Azure Resource sku api 数据链接到 Azure 消费价格表 api 计量数据?
- c# - 如何修复 Microsoft Store 包验证错误:您无法提交预编译的 .NET Native 包?
- shiro - 将登录限制为可调整的角色集的最佳方法
- r - R: NULL 值作为符号地址传递,.Call(RS_PostgreSQL_init, config.params, force) 中的错误: