Hibernate Persist Example

In hibernate; an entity or a record can be saved in a database using the save(), persist(), or the saveOrUpdate() method. In this tutorial, will explore the use of persist() method to commit an entity to the database.

1. Introduction

  • Object-Relational Mapping or ORM is the programming technique to map application domain model objects to the relational database tables
  • Hibernate is a Java-based ORM tool that provides the framework for mapping application domain objects to the relational database tables and vice versa. It provides the reference implementation of Java Persistence API that makes it a great choice as an ORM tool with benefits of loose coupling
  • A Framework that an option to map plain old Java objects to the traditional database tables with the use of JPA annotations as well as XML based configuration

Hibernate Persist - Hibernate Overview
Fig. 1: Hibernate Overview

1.1 Hibernate Annotations

  • Hibernate annotations are the newest way to define mappings without the use of a XML file
  • Developers use annotations to provide metadata configuration along with the Java code. Thus, making the code easy to understand
  • XML provides the ability to change the configuration without building the project. Thus, annotations are less powerful than the XML configuration and should only be used for table and column mappings
  • Annotations are preconfigured with sensible default values, which reduce the amount of coding required. For e.g., Class name defaults to Table name and Field names default to Column names

1.2 Hibernate persist() method

The persist() method in hibernate saves an object in the database and returns a void. This method will throw an exception if the object already exists in the database. Similar to the persist() method, there exists a save() method also. Let’s understand the differences between these two.

The return type of the save() is a Serializable objectThe return type of the persist() is void
Save the changes to the database outside of the transactionDoes not save the changes to the database outside of the transaction
session.save() for a detached object will create a new row in the tablesession.persist() for a detached object will throw the PersistentObjectException as it is not allowed
save() is only supported by Hibernatepersist() is supported by both JPA and Hibernate

1.3 Download and Install Hibernate

You can read this tutorial in order to download and install Hibernate in the Eclipse IDE.

1.4 Download and Install MySQL

You can watch this video in order to download and install the MySQL database on your Windows operating system.

Now, open up the Eclipse IDE and let us see how to implement this method in the hibernate framework!

2. Hibernate Persist Example

Here is a systematic guide for implementing this tutorial in the hibernate framework.

2.1 Tools Used

We are using Eclipse Kepler SR2, JDK 8, MySQL database and Maven. Having said that, we have tested the code against JDK 1.7 and it works well.

2.2 Project Structure

Firstly, let us review the final project structure, in case you are confused about where you should create the corresponding files or folder later!

Hibernate Persist - Application Project Structure
Fig. 2: Application Project Structure

2.3 Project Creation

This section will demonstrate how to create a Java-based Maven project with Eclipse. In Eclipse IDE, go to File -> New -> Maven Project.

Hibernate Persist - Create a Maven Project
Fig. 3: Create a Maven Project

In the New Maven Project window, it will ask you to select the project location. By default, ‘Use default workspace location’ will be selected. Select the ‘Create a simple project (skip archetype selection)’ checkbox and just click on the next button to proceed.

Hibernate Persist - Project Details
Fig. 4: Project Details

It will ask you to ‘Enter the group and the artifact id for the project’. We will input the details as shown in the below image. The version number will be by default: 0.0.1-SNAPSHOT.

Hibernate Persist - Archetype Parameters
Fig. 5: Archetype Parameters

Click on Finish and the creation of a maven project is completed. If you observe, it has downloaded the maven dependencies and a pom.xml file will be created. It will have the following code:


<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">
	<name>Hibernate Persist Example</name>

We can start adding the dependencies that developers want like Hibernate, MySQL etc. Let us start building the application!

3. Application Building

Below are the steps involved in developing this application.

3.1 Database and Table Creation

The following script creates a database called persistdb with a table: employee. Open MySQL terminal and execute the script.


USE persistdb;

CREATE TABLE employee (
	designation VARCHAR(200) DEFAULT NULL,
	department VARCHAR(200) DEFAULT NULL,

If everything goes well, the table will be created.

Hibernate Persist - Database and Table Creation
Fig. 6: Database and Table Creation

3.2 Maven Dependencies

Here, we specify the dependencies for the Hibernate framework and the MySQL connector. Maven will automatically resolve the rest dependencies such as Hibernate Core, MySQL etc. The updated file will have the following code:


<?xml version="1.0" encoding="UTF-8"?>
<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">
   <name>Hibernate Persist Example</name>
      <!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-core -->
      <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->

3.3 Java Class Creation

Let us write the Java classes involved in this application.

3.3.1 Implementation of Model Class

Add the following code to the model definition to map the attributes with the column names.


package com.hibernate.model;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedQuery;
import javax.persistence.Table;

@Table(name= "employee")

@NamedQuery(name= "findEmployees", query="from Employee e")
public class Employee {

	@GeneratedValue(strategy= GenerationType.IDENTITY)
	private int id;
	private String name;
	private String designation;
	private String department;

	public int getId() {
		return id;
	public void setId(int id) {
		this.id = id;
	public String getName() {
		return name;
	public void setName(String name) {
		this.name = name;
	public String getDesignation() {
		return designation;
	public void setDesignation(String designation) {
		this.designation = designation;
	public String getDepartment() {
		return department;
	public void setDepartment(String department) {
		this.department = department;

	public String toString() {
		return "Employee [id=" + id + ", name=" + name + ", designation=" + designation + ", department=" + department
				+ "]";

3.3.2 Implementation of Utility Class

Add the following code to the implementation class for testing the persist() method.


package com.hibernate.util;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

import com.hibernate.model.Employee;

public class AppMain {

	public static void main(String[] args) {		
		// Creating the config instance & passing the hibernate config file.
		Configuration config = new Configuration();

		// Session object to start the db transaction.
		Session s = config.buildSessionFactory().openSession();

		// Transaction object to begin the db transaction.
		Transaction t = s.beginTransaction();
		// Employee object.
		Employee e = new Employee();
		e.setDesignation("Technical Lead");
		e.setDepartment("Software Development");

		// Saving the employee object to the db.

		// Committing the transaction in the db.

		// Query - To fetch all employees.
		List<Employee> list = s.getNamedQuery("findEmployees").getResultList();

		for(Employee emp : list) {

		// Closing the session object.

3.4. Hibernate Configuration File

In the configuration file, we will include the database and the mapping class details.


<?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">
		<!-- Database connection settings -->
		<property name="hibernate.connection.driver_class">com.mysql.cj.jdbc.Driver</property>
		<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/persistdb</property>
		<property name="hibernate.connection.username">root</property>
		<property name="hibernate.connection.password" />

		<!-- Automatic creation or validation of DDL schema -->
		<property name="hibernate.hbm2ddl.auto">validate</property>

		<!-- Sql dialect -->
		<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>

		<!-- Printing the sql queries to the console -->
		<property name="show_sql">true</property>

		<!-- Model class -->
		<mapping class="com.hibernate.model.Employee" />

Important points:

  • Here, we instructed Hibernate to connect to a MySQL database named persistdb and the mapping class to be loaded
  • We have also instructed the Hibernate framework to use MySQLDialect i.e. Hibernate will optimize the generated SQL statements for MySQL
  • This configuration will be used to create a hibernate SessionFactory object
  • show_sql tag will instruct the hibernate framework to log all the SQL statements on the console

4. Run the Application

To run the Hibernate application, Right-click on the AppMain class -> Run As -> Java Application. Developers can debug the example and see what happens after every step!

Hibernate Persist - Run Application
Fig. 7: Run Application

5. Project Demo

The code shows the following logs as the output of this tutorial.

Oct 25, 2018 3:40:28 PM org.hibernate.hql.internal.QueryTranslatorFactoryInitiator initiateService
INFO: HHH000397: Using ASTQueryTranslatorFactory
Hibernate: insert into employee (department, designation, name) values (?, ?, ?)


Hibernate: select employee0_.id as id1_0_, employee0_.department as departme2_0_, employee0_.designation as designat3_0_, employee0_.name as name4_0_ from employee employee0_
Employee [id=1, name=Andrew, designation=Technical Lead, department=Software Development]

That is all for this tutorial and I hope the article served you whatever you were looking for. Happy Learning and do not forget to share!

6. Conclusion

This post defines the implementation of the persist() method in the Hibernate framework and helps developers understand the basic configuration required to achieve this. Developers can download the sample application as an Eclipse project in the Downloads section.

7. Download the Eclipse Project

This was an example of the Hibernate persist method for beginners.

You can download the full source code of this example here: HibernatePersist


An experience full-stack engineer well versed with Core Java, Spring/Springboot, MVC, Security, AOP, Frontend (Angular & React), and cloud technologies (such as AWS, GCP, Jenkins, Docker, K8).
Notify of

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Inline Feedbacks
View all comments
Back to top button