简体   繁体   English

Hibernate:如何级联未映射的实体?

[英]Hibernate: How to cascade unmapped entity?

Is it possible to set cascade without mapping one to many relationships? 是否可以在不映射一对多关系的情况下设置级联?

I have two entities: 我有两个实体:

@Entity
@Table(name = "USER")
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "ID")
    private Long id;

    ...
}

and

@Entity
@Table(name = "RECORD")
public class Record  {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "ID")
    private Long id;

    @ManyToOne
    @JoinColumn(name = "USER")
    private User user;

    ...
}

If I try to delete a user and there exists any record of that user it obviously fails because of the foreign key. 如果我尝试删除一个用户,并且存在该用户的任何记录,则显然是由于外键失败。 I would like to delete all of the user's records before deleting the user. 我想在删除用户之前删除所有用户记录。 I see two options: 我看到两个选择:

  1. Map Record s as @OneToMany relationship in User and set cascade . User @OneToMany Record映射为@OneToMany关系并设置cascade

     @OneToMany(mappedBy = "user", cascade = CascadeType.REMOVE) private Set<Record> records; 
  2. Delete them manually before deleting user 在删除用户之前手动删除它们

Is there any third option, how to set cascade without mapping records in the user entity? 有没有第三种选择,如何设置级联而不在用户实体中映射记录?

级联对JPA不利,最好手动处理。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM