Hibernate OneToMany / ManyToOne删除Cascade

时间:2017-05-04 05:54:38

标签: hibernate

我正在尝试创建OneToMany / ManyToOne关系。除删除操作外,所有操作都按预期工作,这意味着,当删除OwningSide时,NonOwningSide也会被删除。

有没有办法防止这种行为,所以如果删除OwningSide,NonOwningSide的owningSide_id将被设置为NULL?

伪代码

public class OwningSide {

  @OneToMany(
      cascade = {CascadeType.ALL},
      mappedBy = "owningSide")
  @LazyCollection(LazyCollectionOption.FALSE)
  @JsonManagedReference  
  private List<NonOwningSide> nonOwningSide;

}

public class NonOwningSide {

  @ManyToOne(
      cascade = {CascadeType.ALL},
      fetch = FetchType.EAGER)
  @JoinColumn(name = "owningSide_id")
  @JsonBackReference
  private OwningSide owningSide;

}

2 个答案:

答案 0 :(得分:1)

首先在自己身边更改 cascade = CascadeType.PERSIST

public class OwningSide {

  @OneToMany(
      cascade = {CascadeType.PERSIST}, mappedBy = "owningSide")
  @LazyCollection(LazyCollectionOption.FALSE)
  @JsonManagedReference  
  private List<NonOwningSide> nonOwningSide;

}

public class NonOwningSide {

  @ManyToOne(
      cascade = {CascadeType.ALL}, fetch = FetchType.EAGER)
  @JoinColumn(name = "owningSide_id")
  @JsonBackReference
  private OwningSide owningSide;

}

JPA中的CascadeType。 值cascade=ALL相当于  * cascade={PERSIST, MERGE, REMOVE, REFRESH, DETACH}

/** Cascade all operations */
ALL,

/** Cascade persist operation */
PERSIST,

/** Cascade merge operation */
MERGE,

/** Cascade remove operation */
REMOVE,

/** Cascade refresh operation */
REFRESH

要执行此操作,在创建表并向NonOwningSide添加外键时,请提及级联类型为set null以删除owningSide,如下所示。

- 这次,使用 on delete set null

创建它
alter table NonOwningSide add constraint constraintName 
foreign key (id) references OwningSide(id) on delete set null

答案 1 :(得分:0)

你必须将cjild的对象设置为null

for (NonOwningSide child : OwningSide.getChildren()) {
child.setNonOwningSide(null);

} 使用Session.delete(OwningSide);