HomeHibernateHow to persist an Entity in Database using JPA?

How to persist an Entity in Database using JPA?

Table Structure in Database

jpa student table

Technologies Used in example :

  • JPA 2.1
  • Hibernate 5.2.6
  • MySql 8.0
  • Maven 3
  • Spring Tool Suite (STS) 3.9.8
  • Java 1.8

Persistence.xml (Where Database configuration provided)

<persistence-unit name="jbd-pu">
        <property name="javax.persistence.jdbc.driver" value="com.mysql.cj.jdbc.Driver" />
        <property name="javax.persistence.jdbc.url" 
          value="jdbc:mysql://localhost:3306/jpa_jbd?useJDBCCompliantTimezoneShift=true" />
        <property name="javax.persistence.jdbc.user" value="root" />
        <property name="javax.persistence.jdbc.password" value="password" />
        <property name="hibernate.show_sql" value="true" />
        <property name="hibernate.dialect" value="org.hibernate.dialect.MySQLInnoDBDialect"/>

Mapping Studen.java class

public class Student {
	@GeneratedValue(strategy=GenerationType.AUTO, generator="native")
		    name = "native",
		    strategy = "native"
	@Column(name = "ID")
	private Long studentId;
	@Column(name = "FNAME")
	private String firstName;
	@Column(name = "LNAME")
	private String lastName;
	@Column(name = "CONTACT_NO")
	private String contactNo;

    // Setters Getters

Quick look on annotations :

  • Student.java class mapped to the Student table in database.
  • @Entity: Represents that Student.java class is mapped to Student table in DB.
  • @Id : Specifies the primary key property or field of an entity. To map field to the primary key column in table.
  • @GeneratedValue : Provides for the specification of generation strategies for the values of primary keys.
  • GenerationType : Defines the types of primary key generation. In this case autoincrement in Mysql database.
  • @column : Is used to map with specific table column. By default each field is mapped to a column with the name of the field. However if column names are different than the field names , then they can be specified @Column(name=”COLUMN_NAME”).

Saving Entity to the Database :

  • To Save Entity in DB:
    1. Create EntityManagerFactory.
    2. Create EntityManager using EntityManagerFactory.
    3. Get Transaction by using EntityManager.
    4. call the Transaction’s begin();
    5. call the EntityManger’s persist(Entity);
    6. commit the transaction.
  • Persistence.createEntityManagerFactory(“jbd-pu”) – returns EntityManagerFactory and it uses persistence unit and it finds processes the persistence meta information.


  • The persist operation must be used for only new entities. When you create new entity, it’s in the transient entity lifecycle .
  • A transient state entity is not associated with any database table record and it’s not managed by persistence context.
  • To save an entity to database you need to attach entity to persistence context and they become managed. You can use EntityManager’s persist operation to persist an entity in DB
  • And persisted entity lifecycle state becomes Persistent and can be managed with in current persistence context.
public class App 
    public static void main( String[] args )
    	EntityManagerFactory emf = null;
		EntityManager entityManager = null;
		EntityTransaction transaction = null;
			emf = Persistence.createEntityManagerFactory("jbd-pu");
			entityManager = emf.createEntityManager();
			transaction = entityManager.getTransaction();
			Student student = new Student();
		}catch(Exception e){

You will see like following output in console.

Hibernate: insert into STUDENT (CONTACT_NO, FNAME, LNAME) values (?, ?, ?)
Feb 14, 2020 5:44:35 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl stop
INFO: HHH10001008: Cleaning up connection pool [jdbc:mysql://localhost:3306/jpa_jbd?useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC&useSSL=false]

Read more :

  1. Update an entity to the database using JPA.
  2. Merge detached entity to the database using JPA.

Download Application – JPA-Helloworld.zip (16 KB)


Please enter your comment!
Please enter your name here