在使用@OneToMany注解时,如果想要删除子实体而不删除父实体,可以使用cascade属性。该属性指定了在父实体被删除时,如何处理关联的子实体。
以下是一个示例代码:
@Entity
public class ParentEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@OneToMany(mappedBy = "parent", cascade = CascadeType.REMOVE)
private List children;
// getters and setters
}
@Entity
public class ChildEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@ManyToOne
@JoinColumn(name = "parent_id")
private ParentEntity parent;
// getters and setters
}
在上述示例中,ParentEntity和ChildEntity之间使用了@OneToMany和@ManyToOne注解进行关联。在ParentEntity的children属性上,我们使用了cascade = CascadeType.REMOVE,表示在删除父实体时,同时删除关联的子实体。
这样,当我们删除一个ParentEntity对象时,关联的ChildEntity对象也会被自动删除。但是,如果我们只删除ChildEntity对象,不会影响ParentEntity对象。
请注意,cascade属性还可以使用其他级联操作,例如CascadeType.PERSIST(级联持久化)、CascadeType.MERGE(级联合并)等,根据具体需求进行设置。