In Hibernate framework, an entity object can be persisted or saved into database using the following methods –
- save() → This method is used to save an entity object into database and returns a generated identifier or primary key. This method throws an exception if an entity already exists in the database.
- persist() → This method is used to save an entity object into database and returns a void. This method will also throw an exception if an entity already exists in the database.
- saveOrUpdate() → This method is used to either save or update an entity in the database.
All above methods are available in Sesssion interface
The following project will demonstrate the use of the above methods.
Technologies and tools used for this application are -
- Hibernate 5.2.11.Final
- Eclipse Mars.2 (4.5.0)
- Maven 3.5.0
- JavaSE 1.8
- MySQL 5.5.57
Project Structure
Review the following project structure.
Step 1 – Create a maven project
Refer below link if you don’t know how to create Maven project in eclipse:
Step 2 – Add jar dependencies to pom.xml
below is the pom.xml file and add required Hibernate and MySQL connector dependencies to it.
pom.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
<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>com.infotech</groupId> <artifactId>HibernateSaveAndPersistExample</artifactId> <version>0.0.1-SNAPSHOT</version> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> </properties> <dependencies> <!-- MySQL connector dependency --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>6.0.5</version> </dependency> <!-- Hibernate 5.2.11 Final dependency--> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>5.2.11.Final</version> </dependency> </dependencies> <build> <sourceDirectory>src/main/java</sourceDirectory> <plugins> <plugin> <artifactId>maven-compiler-plugin</artifactId> <version>3.5.1</version> <configuration> <source>1.8</source> <target>1.8</target> </configuration> </plugin> </plugins> </build> </project> |
Step 3 – Create a Hibernate configuration file
Create an XML file named as hibernate.cfg.xml under src/main/resources folder and write the following code in it.
hibernate.cfg.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
<?xml version='1.0' encoding='utf-8'?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD//EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <property name="hibernate.connection.driver_class">com.mysql.cj.jdbc.Driver</property> <property name="hibernate.connection.url">jdbc:mysql://localhost:4406/test</property> <property name="hibernate.connection.username">root</property> <property name="hibernate.connection.password">root</property> <property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property> <property name="hibernate.hbm2ddl.auto">update</property> <property name="hibernate.show_sql">true</property> <property name="hibernate.format_sql">true</property> <mapping class="com.infotech.entities.Employee"/> </session-factory> </hibernate-configuration> |
Step 4 – Hibernate utility class which is responsible to provide SessionFactory
Create a class named as HibernateUtil.java as below:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
package com.infotech.util; import org.hibernate.SessionFactory; import org.hibernate.boot.Metadata; import org.hibernate.boot.MetadataSources; import org.hibernate.boot.registry.StandardServiceRegistry; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; /** * @author kishan Kumar */ public class HibernateUtil { private static StandardServiceRegistry standardServiceRegistry; private static SessionFactory sessionFactory; static{ if (sessionFactory == null) { try { // Create StandardServiceRegistry standardServiceRegistry = new StandardServiceRegistryBuilder() .configure() .build(); // Create MetadataSources MetadataSources metadataSources = new MetadataSources(standardServiceRegistry); // Create Metadata Metadata metadata = metadataSources.getMetadataBuilder().build(); // Create SessionFactory sessionFactory = metadata.getSessionFactoryBuilder().build(); } catch (Exception e) { e.printStackTrace(); if (standardServiceRegistry != null) { StandardServiceRegistryBuilder.destroy(standardServiceRegistry); } } } } //Utility method to return SessionFactory public static SessionFactory getSessionFactory() { return sessionFactory; } } |
Step 5 – Create Entity class in hibernate
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 |
package com.infotech.entities; import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name="employee_table") public class Employee { @Id @Column(name="employee_id") @GeneratedValue(strategy=GenerationType.IDENTITY) private Integer employeeId; @Column(name="employee_name",length=100,nullable=false) private String employeeName; @Column(name="email",unique=true) private String email; @Column(name="date_of_joing") private Date doj; @Column(name="salary") private Double salary; public Integer getEmployeeId() { return employeeId; } public void setEmployeeId(Integer employeeId) { this.employeeId = employeeId; } public String getEmployeeName() { return employeeName; } public void setEmployeeName(String employeeName) { this.employeeName = employeeName; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public Date getDoj() { return doj; } public void setDoj(Date doj) { this.doj = doj; } public Double getSalary() { return salary; } public void setSalary(Double salary) { this.salary = salary; } } |
Step 6 – Create a main class and run application
Here is the Client class which shows how to use save(),persist and saveOrUpdate() methods
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 |
package com.infotech.client; import java.util.Date; import org.hibernate.HibernateException; import org.hibernate.Session; import com.infotech.entities.Employee; import com.infotech.util.HibernateUtil; public class ClientTest { public static void main(String[] args) { try(Session session = HibernateUtil.getSessionFactory().openSession()) { session.beginTransaction(); /* persist() -> This method is used to save an entity object into database and return a void. *if an entity already exists in the database the It will throw an exception */ session.persist(getEmployee1()); /* save() -> This method is used to save an entity object into database and return generated primary key. If an entity already exists in the database then It will throw an exception. */ Integer id =(Integer)session.save(getEmployee2()); System.out.println("Employee is created with Id::"+id); //saveOrUpdate()->This method is basically used to either save or update an entity in the database. session.saveOrUpdate(getEmployee3()); session.getTransaction().commit(); } catch (HibernateException e) { e.printStackTrace(); } } private static Employee getEmployee3(){ Employee employee= new Employee(); employee.setEmployeeName("Martin Bingel"); employee.setSalary(80000.00); employee.setDoj(new Date()); return employee; } private static Employee getEmployee1(){ Employee employee= new Employee(); employee.setEmployeeName("Frank Bingel"); employee.setSalary(30000.00); employee.setDoj(new Date()); return employee; } private static Employee getEmployee2(){ Employee employee= new Employee(); employee.setEmployeeName("Sean Bingel"); employee.setSalary(60000.00); employee.setDoj(new Date()); return employee; } } |
That’s all about Save and persist an entity example in hibernate
You May Also Like:
Latest hibernate distribution Zip file download link
Hibernate 5 distribution binary details
Create SessionFactory in Hibernate5 using hibernate.cfg.xml
Create SessionFactory in Hibernate5 without hibernate.cfg.xml
Hibernate CRUD(Create,Read,Update and Delete) example
Dirty checking in hibernate example
Understanding hibernate Configuration File
Why to use hibernate dialect?
Hibernate hbm2ddl property
What are the benefits of using hibernate?
If you have any feedback or suggestion please feel free to drop in below comment box.