May 27 2015

Hibernate cascade types

Hibernate cascade types

Cascading means that if you do any operation on an object it acts on the related objects as well. If you insert, update or delete an object the related objects (mapped objects) are inserted, updated or deleted.

Hibernate does not navigate to object associations when you are performing an operation on the object. If you do not use cascade, you have to do the operations like save, update or delete on each and every object explicitly.

To enable cascading for related association, the cascade attribute has to be configured for association in mapping metadata

Hibernate cascade types

Type Operation
none No cascading(default)
persist persist()
save-update save() and update()
delete delete()
replicate replicate()
refresh refresh()
lock lock()
evict evict()
all save(),update(),delete(),evict(),lock()
delete-orphan delete() + deletes the persistent instance that has been removed(from collection) or dereferenced (object)
all-delete-orphan all + delete-orphan

 

Xml 

  <set name="studentMarks" table="student_marks" cascade="all" lazy="true" >
 <key>
 <column name="STUDENT_ID" />
 </key>
 <one-to-many class="com.answersz.dao.StudentMarks" />
</set>
 

 

Annotation

	@OneToMany(mappedBy = "student")
	@Cascade(CascadeType.ALL)
	private List<StudentMarks> studentMarks;

 

Example

In the below example, Student has ‘one-to-many’ relationship with StudentMarks and Cascade for this relationship is specified as ‘SAVE_UPDATE’. Any save or update operation on Student object will also act on StudentMarks. If cascade is not applied, Student and StudentMarks records has to be saved explicitly.

Student.java


package com.answersz.dao;

import java.util.Date;
import java.util.List;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;

import org.hibernate.annotations.Cascade;
import org.hibernate.annotations.CascadeType;

@Entity
@Table(name = "student")
public class Student {

@Id
 @GeneratedValue(strategy = GenerationType.IDENTITY)
 @Column(name = "STUDENT_ID")
 private Integer studentId;

@Column(name = "STUDENT_NAME")
 private String studentName;

@Column(name = "FATHER_NAME")
 private String fatherName;

@Column(name = "DATE_OF_BIRTH")
 private Date dateofBirth;

@Column(name = "COURSE")
 private String course;

@OneToMany(mappedBy = "student")
 @Cascade(CascadeType.SAVE_UPDATE)
 private List<StudentMarks> studentMarks;

// getters and setters
}

StudentMarks.java 


package com.answersz.dao;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;

@Entity
@Table(name = "student_marks")
public class StudentMarks {

@Id
 @GeneratedValue(strategy = GenerationType.IDENTITY)
 @Column(name = "STUDENT_MARKS_ID")
 private Integer studentMarksId;

@Column(name = "COURSE")
 private String course;

@Column(name = "OBTAINED_MARKS")
 private Integer obtainedMarks;

@Column(name = "TOTAL_MARKS")
 private Integer totalmarks;

@ManyToOne(fetch = FetchType.LAZY)
 @JoinColumn(name = "STUDENT_ID", nullable = false)
 private Student student;

// getters and setters
}

 

HibernateCascadeTypes.java 


package com.answersz.dao;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.AnnotationConfiguration;

// Hibernate cascade types example
public class HibernateCascadeTypes {

public static void main(String[] args) {

SessionFactory factory = new AnnotationConfiguration().configure()
.buildSessionFactory();

Session session = factory.openSession();

Transaction t = session.beginTransaction();

Student student = new Student();
student.setStudentName("PAUL");
student.setFatherName("GEORGE");
student.setDateofBirth(new Date());
student.setCourse("MS");

List<StudentMarks> studentMarksList = new ArrayList<StudentMarks>();

StudentMarks studentMarks = new StudentMarks();
studentMarks.setCourse("JAVA");
studentMarks.setObtainedMarks(80);
studentMarks.setTotalmarks(100);
studentMarks.setStudent(student);

studentMarksList.add(studentMarks);
student.setStudentMarks(studentMarksList);

session.save(student);
t.commit();

session.close();
factory.close();
}

}

 

Output


Hibernate: insert into student (COURSE, DATE_OF_BIRTH, FATHER_NAME, STUDENT_NAME) values (?, ?, ?, ?)
Hibernate: insert into student_marks (COURSE, OBTAINED_MARKS, STUDENT_ID, TOTAL_MARKS) values (?, ?, ?, ?)


Copyright © 2014. All rights reserved.

Posted May 27, 2015 by answersz in category Hibernate

Leave a Comment

Your email address will not be published. Required fields are marked *

*