user3214269
user3214269

Reputation: 219

How to use cascade type save,delete, update in hibernate annotation

Can any one explain me the hibernate annotation how to use different types of cascade like delete,upadte,save-update?

How can I make sure that when an Owner is deleted, its car is deleted as well (but not the other way around)

 @Entity
    public class Owner
    {
        @OneToOne(cascade=CascadeType.ALL)
        private DrivingLicense license;

        @OneToMany(mappedBy="owner", cascade={CascadeType.PERSIST, CascadeType.MERGE})
        private Collection cars;

        ...
    }

    @Entity
    public class DrivingLicense
    {
        private String serialNumber;

        ...
    }

    @Entity
    public class Car
    {
        private String registrationNumber;

        @ManyToOne(cascade={CascadeType.PERSIST, CascadeType.MERGE})
        private Owner owner;

        ...
    }

Upvotes: 3

Views: 29669

Answers (1)

Joeri Hendrickx
Joeri Hendrickx

Reputation: 17435

The pitfall here is that there are two CascadeType enums. One is of javax.persistence, the other is from hibernate. In general I would prefer to use the persistence one.

For cascade update, keep in mind that "update" is a hibernate term, and jpa doesn't know this. Jpa doesnt need it, because in JPA the idea is that your updated fields will flush to the database automatically. If you made any changes in relations, those will flush as well. So you dont need a cascade on update.

For save-update, this is a hibernate shortcut to using either persist or update depending on the state of the object. Since you're already covering persist and update(see above), you dont need a cascade on this.

To cascade a delete, you probably want to use @OrphanRemoval instead. This will make sure that if the parent of a relation is removed, the child is gone, too (but not the other way around).

    @OneToMany(mappedBy="owner", cascade={CascadeType.PERSIST, CascadeType.MERGE})
    @OrphanRemoval
    private Collection cars;

Upvotes: 2

Related Questions