Cascade save-update Project in Hibernate

Let us see one end to end project for Cascade save-update

Step 1

Create hibernate project

Please refer Hibernate setup in eclipse article on how to do it.

Project structure


Cascade_proj_stru

Step 2

Update pom.xml with Hibernate and Mysql dependencies

  1. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  2.   xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  3.   <modelVersion>4.0.0</modelVersion>
  4.  
  5.   <groupId>HibernateCascade</groupId>
  6.   <artifactId>HibernateCascade</artifactId>
  7.   <version>0.0.1-SNAPSHOT</version>
  8.   <packaging>jar</packaging>
  9.  
  10.   <name>HibernateCascade</name>
  11.   <url>http://maven.apache.org</url>
  12.  
  13.   <properties>
  14.     <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  15.   </properties>
  16.  
  17.   <dependencies>
  18.     <dependency>
  19.       <groupId>junit</groupId>
  20.       <artifactId>junit</artifactId>
  21.       <version>3.8.1</version>
  22.       <scope>test</scope>
  23.     </dependency>
  24.      <!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-core -->
  25.         <dependency>
  26.             <groupId>org.hibernate</groupId>
  27.             <artifactId>hibernate-core</artifactId>
  28.             <version>5.2.6.Final</version>
  29.         </dependency>
  30.         <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
  31.         <dependency>
  32.             <groupId>mysql</groupId>
  33.             <artifactId>mysql-connector-java</artifactId>
  34.             <version>6.0.5</version>
  35.         </dependency>
  36.   </dependencies>
  37. </project>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>HibernateCascade</groupId>
  <artifactId>HibernateCascade</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>HibernateCascade</name>
  <url>http://maven.apache.org</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
     <!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-core -->
		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-core</artifactId>
			<version>5.2.6.Final</version>
		</dependency>
		<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>6.0.5</version>
		</dependency>
  </dependencies>
</project>

Step 3

Create Applicant class

  1. package com.kb.model;
  2.  
  3. import java.util.Set;
  4.  
  5. import javax.persistence.Column;
  6. import javax.persistence.Entity;
  7. import javax.persistence.GeneratedValue;
  8. import javax.persistence.GenerationType;
  9. import javax.persistence.Id;
  10. import javax.persistence.OneToMany;
  11. import javax.persistence.Table;
  12.  
  13. import org.hibernate.annotations.Cascade;
  14. import org.hibernate.annotations.CascadeType;
  15.  
  16. @Entity
  17. @Table(name="Applicant")
  18. public class Applicant {
  19.  
  20.     @Id
  21.     @GeneratedValue(strategy = GenerationType.SEQUENCE)
  22.     @Column(name = "Applicant_Id")
  23.     private int applicantId;
  24.    
  25.     @Column(name = "FirstName")
  26.     private String firstName;
  27.    
  28.     @Column(name = "LastName")
  29.     private String lastName;
  30.    
  31.     @Column(name = "Age")
  32.     private int age;
  33.    
  34.     @Column(name = "Education")
  35.     private String education;
  36.    
  37.     @OneToMany(mappedBy="applicant")
  38.     @Cascade(CascadeType.SAVE_UPDATE)
  39.     private Set<Address> addresses;h
  40.    
  41.     public int getApplicantId() {
  42.         return applicantId;
  43.     }
  44.     public void setApplicantId(int applicantId) {
  45.         this.applicantId = applicantId;
  46.     }
  47.     public String getFirstName() {
  48.         return firstName;
  49.     }
  50.     public void setFirstName(String firstName) {
  51.         this.firstName = firstName;
  52.     }
  53.     public String getLastName() {
  54.         return lastName;
  55.     }
  56.     public void setLastName(String lastName) {
  57.         this.lastName = lastName;
  58.     }
  59.     public int getAge() {
  60.         return age;
  61.     }
  62.     public void setAge(int age) {
  63.         this.age = age;
  64.     }
  65.     public String getEducation() {
  66.         return education;
  67.     }
  68.     public void setEducation(String education) {
  69.         this.education = education;
  70.     }
  71.     public Set<Address> getAddresses() {
  72.         return addresses;
  73.     }
  74.     public void setAddresses(Set<Address> addresses) {
  75.         this.addresses = addresses;
  76.     }
  77.  
  78. }
package com.kb.model;

import java.util.Set;

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="Applicant")
public class Applicant {

	@Id
	@GeneratedValue(strategy = GenerationType.SEQUENCE)
	@Column(name = "Applicant_Id")
	private int applicantId;
	
	@Column(name = "FirstName")
	private String firstName;
	
	@Column(name = "LastName")
	private String lastName;
	
	@Column(name = "Age")
	private int age;
	
	@Column(name = "Education")
	private String education;
	
	@OneToMany(mappedBy="applicant")
	@Cascade(CascadeType.SAVE_UPDATE)
	private Set<Address> addresses;h
	
	public int getApplicantId() {
		return applicantId;
	}
	public void setApplicantId(int applicantId) {
		this.applicantId = applicantId;
	}
	public String getFirstName() {
		return firstName;
	}
	public void setFirstName(String firstName) {
		this.firstName = firstName;
	}
	public String getLastName() {
		return lastName;
	}
	public void setLastName(String lastName) {
		this.lastName = lastName;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public String getEducation() {
		return education;
	}
	public void setEducation(String education) {
		this.education = education;
	}
	public Set<Address> getAddresses() {
		return addresses;
	}
	public void setAddresses(Set<Address> addresses) {
		this.addresses = addresses;
	}

}


We can see that we have added Set< Address> in Applicant class to maintain OneToMany relation.

@Cascade(CascadeType.SAVE_UPDATE) – is used to instruct Hibernate to use Cascade on mapped entity(Address) when Save or Update is performed on owner entity(Applicant).

It means whenever we save or update Applicant, its associated Address objects will also be saved automatically.

Step 4

Create Address class

  1. package com.kb.model;
  2.  
  3. import javax.persistence.Column;
  4. import javax.persistence.Entity;
  5. import javax.persistence.GeneratedValue;
  6. import javax.persistence.GenerationType;
  7. import javax.persistence.Id;
  8. import javax.persistence.JoinColumn;
  9. import javax.persistence.ManyToOne;
  10. import javax.persistence.Table;
  11.  
  12. @Entity
  13. @Table(name="Address")
  14. public class Address {
  15.  
  16.     @Id
  17.     @GeneratedValue(strategy = GenerationType.SEQUENCE)
  18.     @Column(name = "Address_Id")
  19.     private int addressId;
  20.    
  21.     @Column(name = "Street")
  22.     private String street;
  23.    
  24.     @Column(name = "City")
  25.     private String city;
  26.    
  27.     @Column(name = "Zipcode")
  28.     private String zipcode;
  29.    
  30.     @ManyToOne
  31.     @JoinColumn(name="Applicant_Id")
  32.     private Applicant applicant;
  33.    
  34.     public int getAddressId() {
  35.         return addressId;
  36.     }
  37.     public void setAddressId(int addressId) {
  38.         this.addressId = addressId;
  39.     }
  40.     public String getStreet() {
  41.         return street;
  42.     }
  43.     public void setStreet(String street) {
  44.         this.street = street;
  45.     }
  46.     public String getCity() {
  47.         return city;
  48.     }
  49.     public void setCity(String city) {
  50.         this.city = city;
  51.     }
  52.     public String getZipcode() {
  53.         return zipcode;
  54.     }
  55.     public void setZipcode(String zipcode) {
  56.         this.zipcode = zipcode;
  57.     }
  58.     public Applicant getApplicant() {
  59.         return applicant;
  60.     }
  61.     public void setApplicant(Applicant applicant) {
  62.         this.applicant = applicant;
  63.     }
  64.  
  65. }
package com.kb.model;

import javax.persistence.Column;
import javax.persistence.Entity;
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="Address")
public class Address {

	@Id
	@GeneratedValue(strategy = GenerationType.SEQUENCE)
	@Column(name = "Address_Id")
	private int addressId;
	
	@Column(name = "Street")
	private String street;
	
	@Column(name = "City")
	private String city;
	
	@Column(name = "Zipcode")
	private String zipcode;
	
	@ManyToOne
	@JoinColumn(name="Applicant_Id")
	private Applicant applicant;
	
	public int getAddressId() {
		return addressId;
	}
	public void setAddressId(int addressId) {
		this.addressId = addressId;
	}
	public String getStreet() {
		return street;
	}
	public void setStreet(String street) {
		this.street = street;
	}
	public String getCity() {
		return city;
	}
	public void setCity(String city) {
		this.city = city;
	}
	public String getZipcode() {
		return zipcode;
	}
	public void setZipcode(String zipcode) {
		this.zipcode = zipcode;
	}
	public Applicant getApplicant() {
		return applicant;
	}
	public void setApplicant(Applicant applicant) {
		this.applicant = applicant;
	}

}


We can see that we have added Applicant in Address class to maintain other side of OneToMany relation which is ManyToOne.

Step 5

Create hibernate.cfg.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!DOCTYPE hibernate-configuration PUBLIC
  3.        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
  4.        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
  5.  
  6. <hibernate-configuration>
  7.  
  8.    <session-factory>
  9.  
  10.        <!-- Database connection properties -->
  11.        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
  12.        <property name="connection.url">jdbc:mysql://localhost/javainsimpleway</property>
  13.        <property name="connection.username">root</property>
  14.        <property name="connection.password">root</property>
  15.  
  16.        <!-- JDBC connection pool (using the built-in) -->
  17.        <property name="connection.pool_size">100</property>
  18.  
  19.        <!-- SQL dialect -->
  20.        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
  21.  
  22.        <!-- Disable the second-level cache -->
  23.        <property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property>
  24.  
  25.        <!-- Echo all executed SQL to stdout -->
  26.        <property name="show_sql">true</property>
  27.        
  28.        <!-- Format the generated Sql -->
  29.        <property name="format_sql">true</property>
  30.  
  31.        <!-- Dont Drop and re-create the database schema on startup,Just update it -->
  32.        <property name="hbm2ddl.auto">update</property>
  33.  
  34.           <mapping class="com.kb.model.Applicant" />
  35.       <mapping class="com.kb.model.Address" />
  36.  
  37.    </session-factory>
  38.  
  39. </hibernate-configuration>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
       "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
       "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
 
<hibernate-configuration>
 
   <session-factory>
 
       <!-- Database connection properties -->
       <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
       <property name="connection.url">jdbc:mysql://localhost/javainsimpleway</property>
       <property name="connection.username">root</property>
       <property name="connection.password">root</property>
 
       <!-- JDBC connection pool (using the built-in) -->
       <property name="connection.pool_size">100</property>
 
       <!-- SQL dialect -->
       <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
 
       <!-- Disable the second-level cache -->
       <property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property>
 
       <!-- Echo all executed SQL to stdout -->
       <property name="show_sql">true</property>
       
       <!-- Format the generated Sql -->
       <property name="format_sql">true</property>
 
       <!-- Dont Drop and re-create the database schema on startup,Just update it -->
       <property name="hbm2ddl.auto">update</property>
 
          <mapping class="com.kb.model.Applicant" />
	  <mapping class="com.kb.model.Address" />
 
   </session-factory>
 
</hibernate-configuration>


We have defined all the database configuration in this file

hbm2ddl.auto property is defined in the config file which helps in automatic creation of tables in the database based on the mapping.

We have also provided the mapping xml file location using < mapping > tag.

Step 6

Create Hibernate util class

  1. package com.kb.util;
  2.  
  3. import org.hibernate.SessionFactory;
  4. import org.hibernate.cfg.Configuration;
  5.  
  6. public class HibernateUtil {
  7.     private static final SessionFactory sessionFactory = buildSessionFactory();
  8.  
  9.     private static SessionFactory buildSessionFactory() {
  10.         try {
  11.             // Create the SessionFactory from hibernate.cfg.xml
  12.             return new Configuration().configure().buildSessionFactory();
  13.         } catch (Throwable ex) {
  14.             // Make sure you log the exception to track it
  15.             System.err.println("SessionFactory creation failed." + ex);
  16.             throw new ExceptionInInitializerError(ex);
  17.         }
  18.     }
  19.  
  20.     public static SessionFactory getSessionFactory() {
  21.         return sessionFactory;
  22.     }
  23.    
  24.     public static void shutdown() {
  25.         // Optional but can be used to Close caches and connection pools
  26.         getSessionFactory().close();
  27.     }
  28.  
  29. }
package com.kb.util;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateUtil {
	private static final SessionFactory sessionFactory = buildSessionFactory();

    private static SessionFactory buildSessionFactory() {
        try {
            // Create the SessionFactory from hibernate.cfg.xml
            return new Configuration().configure().buildSessionFactory();
        } catch (Throwable ex) {
            // Make sure you log the exception to track it
            System.err.println("SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }

    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }
    
    public static void shutdown() {
    	// Optional but can be used to Close caches and connection pools
    	getSessionFactory().close();
    }

}

Step 7

Create main class to interact with DB

  1. package com.kb.db;
  2.  
  3. import java.util.HashSet;
  4. import java.util.Set;
  5.  
  6. import org.hibernate.Session;
  7. import org.hibernate.SessionFactory;
  8. import org.hibernate.Transaction;
  9.  
  10. import com.kb.model.Address;
  11. import com.kb.model.Applicant;
  12. import com.kb.util.HibernateUtil;
  13.  
  14. public class Main {
  15.     public static void main(String[] args) {
  16.         // Get session factory using Hibernate Util class
  17.         SessionFactory sf = HibernateUtil.getSessionFactory();
  18.         // Get session from Sesson factory
  19.         Session session = sf.openSession();
  20.  
  21.         // Begin transaction
  22.         Transaction t = session.beginTransaction();
  23.         //Create Applicant Model data
  24.         Applicant applicant = new Applicant();
  25.         applicant.setFirstName("John");
  26.         applicant.setLastName("KC");
  27.         applicant.setAge(28);
  28.         applicant.setEducation("Graduation");
  29.  
  30.         //Create Address Model data
  31.         Address currentAdd = new Address();
  32.         currentAdd.setStreet("Royal road");
  33.         currentAdd.setCity("Newyork");
  34.         currentAdd.setZipcode("10001");
  35.         currentAdd.setApplicant(applicant);
  36.        
  37.         Address permanentAdd = new Address();
  38.         permanentAdd.setStreet("Manyar Road");
  39.         permanentAdd.setCity("Sydney");
  40.         permanentAdd.setZipcode("2060");
  41.         permanentAdd.setApplicant(applicant);
  42.        
  43.         Set<Address> addresses = new HashSet<Address>();
  44.         addresses.add(currentAdd);
  45.         addresses.add(permanentAdd);
  46.  
  47.         applicant.setAddresses(addresses);
  48.  
  49.         session.save(applicant);
  50.        
  51.         // Commit the transaction and close the session
  52.         t.commit();
  53.         session.close();
  54.         System.out.println("successfully persisted Applicant details");
  55.     }
  56.  
  57. }
package com.kb.db;

import java.util.HashSet;
import java.util.Set;

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

import com.kb.model.Address;
import com.kb.model.Applicant;
import com.kb.util.HibernateUtil;

public class Main {
	public static void main(String[] args) {
		// Get session factory using Hibernate Util class
		SessionFactory sf = HibernateUtil.getSessionFactory();
		// Get session from Sesson factory
		Session session = sf.openSession();

		// Begin transaction
		Transaction t = session.beginTransaction();
		//Create Applicant Model data
		Applicant applicant = new Applicant();
		applicant.setFirstName("John");
		applicant.setLastName("KC");
		applicant.setAge(28);
		applicant.setEducation("Graduation");

		//Create Address Model data
		Address currentAdd = new Address();
		currentAdd.setStreet("Royal road");
		currentAdd.setCity("Newyork");
		currentAdd.setZipcode("10001");
		currentAdd.setApplicant(applicant);
		
		Address permanentAdd = new Address();
		permanentAdd.setStreet("Manyar Road");
		permanentAdd.setCity("Sydney");
		permanentAdd.setZipcode("2060");
		permanentAdd.setApplicant(applicant);
		
		Set<Address> addresses = new HashSet<Address>();
		addresses.add(currentAdd);
		addresses.add(permanentAdd);

		applicant.setAddresses(addresses);

		session.save(applicant);
		
		// Commit the transaction and close the session
		t.commit();
		session.close();
		System.out.println("successfully persisted Applicant details");
	}

}


We have added 1 Applicant and associated 2 addresses to it and saved only Applicant but Hibernate will take care of saving all addresses as we have used Cascade in the mapping.

Step 8

Run the above class to check the output

Check Table in MYSQL console

E:\MySql_Install\bin
Mysql –u root –p
Enter password

Use javainsimpleway;

Select * from Applicant;

Select * from address;

OneToManyXMLOutput

We can see that both Applcant and Address tables are persisted using Cascade.

Download this project HibernateCascade.zip

About the Author

Founder of javainsimpleway.com
I love Java and open source technologies and very much passionate about software development.
I like to share my knowledge with others especially on technology 🙂
I have given all the examples as simple as possible to understand for the beginners.
All the code posted on my blog is developed,compiled and tested in my development environment.
If you find any mistakes or bugs, Please drop an email to kb.knowledge.sharing@gmail.com

Connect with me on Facebook for more updates

Share this article on