
JPA - Persistence Operations
- JPA - Entity Managers
- JPA - Create Employee Example
- JPA - Update Employee Example
- JPA - Find Employee Example
- JPA - Delete Employee Example
- JPA - Criteria API
JPA - JPQL
- JPA - JPQL
- JPA - Scalar Function
- JPA - Aggregate Function
- JPA - Between Keyword
- JPA - Like Keyword
- JPA - Order By Clause
- JPA - Named Query
JPA - Advanced Mappings
- JPA - Advanced Mappings
- JPA - Single Table Strategy
- JPA - Joined Table Strategy
- JPA - Table per Class Strategy
JPA - Entity Relationships
- JPA - Entity Relationships
- JPA - @ManyToOne Relationships
- JPA - @OneToMany Relationships
- JPA - @OneToOne Relationships
- JPA - @ManyToMany Relationships
JPA - Useful Resources
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 |