Home  >  Hibernate

Example of CascadeType.PERSIST in Hibernate

By Arvind Rai, May 27, 2013
In Hibernate CascadeType.PERSIST plays the role when more than one entity is associated to each other. CascadeType.PERSIST cascades the create operation to all associated entities create. If we persist data in one entity then data will be saved in associated entity if CascadeType.PERSIST is annotated. For example if the entity Country is associated with State and we are saving data of country with given states then table state will also be populated with the given data. In Hibernate we need to call persist() method to persist 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.PERSIST)	
	@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;
}
 
POSTED BY
ARVIND RAI
ARVIND RAI
FIND MORE TUTORILAS






©2019 concretepage.com | Privacy Policy | Contact Us