Save and persist an entity example in hibernate

By | June 9, 2018

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:

How to create Maven project

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

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

Step 4 – Hibernate utility class which is responsible to provide SessionFactory

Create a class named as HibernateUtil.java as below:

Step 5 – Create Entity class in hibernate

 

Step 6 – Create a main class and run application

Here is the Client class which shows how to use save(),persist and saveOrUpdate()  methods

 

Leave a Reply

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