JPA - Create Employee Example



This chapter takes you through simple example with JPA to create an Employee record in the MySQL database. We've created Employee.java as entity and persistence.xml in Entity Managers chapter.

Now let's create a service to create an employee in the database.

Example - Create Employee

CreateEmployee.java

package com.tutorialspoint.eclipselink.service;

import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityManagerFactory;
import jakarta.persistence.Persistence;
import com.tutorialspoint.eclipselink.entity.Employee;

public class CreateEmployee {

   public static void main( String[ ] args ) {
   
      EntityManagerFactory emfactory = Persistence.createEntityManagerFactory( "Eclipselink_JPA" );
      
      EntityManager entitymanager = emfactory.createEntityManager( );
      entitymanager.getTransaction( ).begin( );

      Employee employee = new Employee( ); 
      employee.setEid( 1201 );
      employee.setEname( "Gopal" );
      employee.setSalary( 40000 );
      employee.setDeg( "Technical Manager" );
      
      entitymanager.persist( employee );
      entitymanager.getTransaction( ).commit( );

      entitymanager.close( );
      emfactory.close( );
   }
}

In the above code the createEntityManagerFactory () creates a persistence unit by providing the same unique name which we provide for persistence-unit in persistent.xml file. The entitymanagerfactory object will create the entitymanger instance by using createEntityManager () method. The entitymanager object creates entitytransaction instance for transaction management. By using entitymanager object, we can persist entities into database.

Output

Run the code as Java Application in Eclipse IDE.

After compilation and execution of the above program you will get notifications from eclipselink library on the console panel of eclipse IDE.

For result, open the MySQL workbench and type the following queries.

use jpadb
select * from employee

The effected database table named employee will be shown in a tabular format as follows:

Eid Ename Salary Deg
1201 Gopal 40000 Technical Manager
Advertisements