Cascade is used when multiple objects in entities wants to be saved in a single shot.

For Example

 session.save(objUserDetail1);
 session.save(objVeh1);
 session.save(objVeh2);
 session.save(objVeh3);

can be replaced by

 session.persist(objUserDetail1);

UserDetails.java

@Entity
@Table(name="USER_DETAIL")
public class UserDetails 
{	
	@Id @GeneratedValue(strategy = GenerationType.AUTO)	
	private int UserId;	
	private String UserName;
	
	@OneToMany(cascade=CascadeType.PERSIST)
	private List<Vehicles> arrVehicles = new ArrayList<Vehicles>();
	  
	public List<Vehicles> getArrVehicles() {
		return arrVehicles;
	}
	public void setArrVehicles(List<Vehicles> arrVehicles) {
		this.arrVehicles = arrVehicles;
	}
	
	public int getUserId() {
		return UserId;
	}
	public void setUserId(int userId) {
		UserId = userId;
	}
	public String getUserName() {
		return UserName;
	}
	public void setUserName(String userName) {
		UserName = userName;
	}
}

CreateTables.java

public static void main(String[] args) 
  {	
	UserDetails objUserDetail1 =  new UserDetails();
	objUserDetail1.setUserName("Mugil");

	Vehicles objVeh1 = new Vehicles();
	objVeh1.setVehicleName("Suzuki");
	objUserDetail1.getArrVehicles().add(objVeh1);

	Vehicles objVeh2 = new Vehicles();
	objVeh2.setVehicleName("Maruthi");
	objUserDetail1.getArrVehicles().add(objVeh2);

	Vehicles objVeh3 = new Vehicles();
	objVeh3.setVehicleName("Volkswagon");
	objUserDetail1.getArrVehicles().add(objVeh3);
							
	SessionFactory sessionFact = createSessionFactory();
	Session session = sessionFact.openSession();

	session.beginTransaction();				
	session.persist(objUserDetail1);		

	session.getTransaction().commit();
	session.close();  
  }

Comments are closed.