简体   繁体   中英

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 .

     @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不利,最好手动处理。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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