我有一个带有两个外键和多对一关联(到表checkpoint和setting)的表选项:db schema。
从 JPA 方面,我有 2 个双向关联:一方面是 Cascade.ALL和FetchType.EAGER,另一方面是Cascade.REMOVE。这是相应的 JPA 映射:
@Entity
@Table(name = "checkpoint")
@AllArgsConstructor
@NoArgsConstructor
@Data
public class Checkpoint {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
private long location;
@OneToMany(mappedBy = "checkpoint",
cascade = CascadeType.ALL,
orphanRemoval = true,
fetch = FetchType.EAGER)
private List<RewardOption> rewardOptions = new ArrayList<>();
}
@Entity
@Table(name = "setting")
@AllArgsConstructor
@NoArgsConstructor
@Data
public class RewardSetting {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
@Column(name = "base_line")
private long baseLine;
@OneToMany(mappedBy = "rewardSetting",
cascade = CascadeType.REMOVE,
orphanRemoval = true)
private List<RewardOption> rewardOptions = new ArrayList<>();
}
@Entity
@Table(name = "option")
@AllArgsConstructor
@NoArgsConstructor
@Data
public class RewardOption {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
private long weight;
@ManyToOne
@JoinColumn(name = "setting_id")
private RewardSetting rewardSetting;
@ManyToOne
@JoinColumn(name = "checkpoint_id")
private Checkpoint checkpoint;
}
此外,我正在使用 Spring Data 进行实体操作。对我来说,这似乎是一个有效的例子,但在我表演时的练习中:
...
rewardSettingRepository.delete(rewardSetting);
或者:
...
rewardSettingRepository.delete(id);
我让 JPA 尝试在选项表中的相应行之前从设置表中删除一行。
有没有人有一些想法为什么它会这样?为什么这种映射会导致这种行为?如何正确地做到这一点?
繁星淼淼
相关分类