Example of CascadeType.MERGE in Hibernate
May 27, 2013
In Hibernate CascadeType.MERGE plays the role when more than one entity is associated to each other. CascadeType.MERGE cascades the merge operation to all associated entities merge. If one entity is merged, other associated entities will also be merged in case CascadeType.MERGE is annotated. For example if the entity Country is associated with State and we are merging entity states, both the entities Country and State will be merged with current states of hibernate persistence. In Hibernate we need to call merge() method to merge the entity.
Country.java
@Entity public class Country implements Serializable { private static final long serialVersionUID = 1L; @Id @Column(name="id") private int id; @Column(name="name") private String name; @OneToMany(cascade=CascadeType.MERGE) @JoinColumn( name="id") private Set<State> states; }
State.java
@Entity @Table(name = "state") public class State implements Serializable{ private static final long serialVersionUID = 1L; @Id @Column(name = "id") private int id; @Id @Column(name = "country_id") private int countryId; @Column(name = "name") private String name; }