abdelhady
abdelhady

Reputation: 560

Hibernate cascade child

I using Hibernate and spring data to manage my entity with oracle DB

I have the following Entity

@Entity
@Table(name = "user")
public class User {    
    @Id 
    @GeneratedValue(strategy = GenerationType.SEQUENCE)
    private Long id;
    @NotNull
    private String title;
}

and another one

@Entity
@Table(name = "user_detail")
public class UserDetail {    
    @Id 
    @GeneratedValue(strategy = GenerationType.SEQUENCE)
    private Long id;
    private String address;
    @ManyToOne
    @JoinColumn(name = "user_id")
    private User user;
}

I want when delete user the child 'user detail' also deleted (cascade) How to solve this problem with hibernate

Upvotes: 2

Views: 258

Answers (2)

abdelhady
abdelhady

Reputation: 560

The Solution is to add On Delete annotation '@OnDelete(action=OnDeleteAction.CASCADE)' above the relation Like below:

@Entity
@Table(name = "user_detail")
public class UserDetail {    
    @Id 
    @GeneratedValue(strategy = GenerationType.SEQUENCE)
    private Long id;
    private String address;
    @ManyToOne
    @JoinColumn(name = "user_id")
    @OnDelete(action=OnDeleteAction.CASCADE)
    private User user;
}

Upvotes: 0

Renan Scarela
Renan Scarela

Reputation: 357

In order to perform cascades, you'll have to do a few changes in your code.

First of all, you'll have to map UserDetail in User entity and include a cascade setup in your relational annotation:

@Entity
@Table(name = "user")
public class User {    
    @Id 
    @GeneratedValue(strategy = GenerationType.SEQUENCE)
    private Long id;

    @NotNull
    private String title;

    @OneToOne(mappedBy="user", cascade=CascadeType.ALL)
    private UserDetail detail;
}

PS: I'm assuming one to one relation, but feel free to map as you wish...all hibernate's relational annotations supports cascade. Mapped collections are supported as well.

By doing this, you are telling Hibernate to perform cascade whenever it performs an operation on an User entity. In case you want to tell exactly on which operations it must perform the cascade, you can do this:

@Entity
@Table(name = "user")
public class User {    
    @Id 
    @GeneratedValue(strategy = GenerationType.SEQUENCE)
    private Long id;

    @NotNull
    private String title;

    @OneToOne(mappedBy="user", cascade={CascadeType.PERSIST, CascadeType.DELETE})
    private UserDetail detail;
}

You can find all CascadeTypes on Hibernate docs. Just notice that, in order to perform cascades, you should avoid using hibernate's session "update", "save" and "saveOrUpdate" methods...you should use "persist" and "merge".

Upvotes: 2

Related Questions