猿问

Spring Data 映射无法按预期工作

我有一个带有两个外键和多对一关联(到表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 尝试在选项表中的相应行之前从设置表中删除一行。


有没有人有一些想法为什么它会这样?为什么这种映射会导致这种行为?如何正确地做到这一点?


慕尼黑5688855
浏览 132回答 1
1回答

繁星淼淼

要使其工作,您需要同步双向关联的两端。这意味着,在调用 delete 之前,您需要确保将父实体与所有子实体分离。
随时随地看视频慕课网APP

相关分类

Java
我要回答