Hi,Hope you are doing well.
This post is focused on JPA Framework Module.Let Start with JPA introduction
What is JPA?
The Java Persistence API (JPA) is the Java standard for mapping Java objects to a relational database.
Mapping Java objects to database tables and vice versa is called Object-relational mapping (ORM). The Java Persistence API (JPA) is one possible approach to ORM via JPA the developer can map, store, update and retrieve data from relational databases to Java objects and vice versa.
JPA can be used in Java-EE and Java-SE applications.
Persistence in this context covers three areas:
the API itself, defined in the javax.persistence package
the Java Persistence Query Language (JPQL)
object/relational metadata
JPA is a specification and several implementations are available. Popular implementations are Hibernate, EclipseLink and Apache OpenJPA.
What are the advantages of JPA?
The advantages of JPA are given below.
The burden of interacting with the database reduces significantly by using JPA
The user programming becomes easy by concealing the O/R mapping and database access processing
The cost of creating the definition file is reduced by using annotations
We can merge the applications used with other JPA providers
Using different implementations can add the features to the standard Implementation which can later be the part of JPA specification
First Program of JPA:
Here, we are using JPA to perform create, delete, update and delete methods, as shown below:
Employee Class
The Employee class is an entity class, annotated with the javax.persistence.Entity annotation. It uses the @Id annotation to define its id property.
package com.codersarts.emp;
import javax.persistence.*;
@Entity
publicclass Employee {
@Id String name;
Double salary;
public Employee()
{
}
public Employee (String name, Double Salary)
{
this.name=name;
this.salary=Salary;
}
publicvoid setSalary(Double Salary)
{
this.salary=Salary;
}
publicString toString()
{
return"Name: "+name+"nSalary: "+salary ;
}
}
MAIN Program
In the MAIN Program we create four methods, displayAll(), insert(), delete(String name) and modify(String name, Double Salary) to perform the CRUD functionality. In all methods we use an EntityManager, using the createEntityManager() API method. The getTransaction().begin() and getTransaction().commit() methods are used before and after the EntityManager invokes a method so that a transaction begins and ends.
In displayAll() method we use the createQuery(java.lang.String qlString, java.lang.Class<T> resultClass) method to create an instance of TypedQuery for executing a Java Persistence query language statement. Then using the getResultList() method of Query we get the list of the results.
In insert() method a new object is written to the database, using the persist(java.lang.Object entity) API method of EntityManager.
In delete(String name) method an Employee object can be retrieved using the find(java.lang.Class<T> entityClass, java.lang.Object primaryKey) API method of EntityManager. Then it can be removed using the remove(java.lang.Object entity) API method of EntityManager.
In modify(String name, Double Salary) method an Employee object can be retrieved using the find(java.lang.Class<T> entityClass, java.lang.Object primaryKey) API method of EntityManager. Then a field of the object can be modified using its setter.
package com.codersarts.emp;
import javax.persistence.*;
import java.util.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main {
/**
* Displays all Employees in the Database
*/
private static void displayAll()
{
em.getTransaction().begin();
TypedQuery e=em.createQuery(displayAllQuery, Employee.class);
List <Employee> employees=e.getResultList();
if(employees.size()>0)
{
for(Employee temp:employees)
{
System.out.println(temp);
System.out.println();
}
System.out.println(employees.size()+" Employee Records Available...!");
}
else
System.out.println("Database is Empty!");
em.getTransaction().commit();
}
/**
* Insets an Employee into the Database.
*/
private static void insert()
{
System.out.print("Enter the number of Employees to be inserted: ");
n=input.nextInt();
em.getTransaction().begin();
for(int i=0;i<n;i++)
{
System.out.println("Enter the details of Employee "+(i+1)+": ");
System.out.print("Name: ");
//I use BufferedReader to read String and hence I need to
// Catch the IOException that it may throw
try
{
name=bufferedReader.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
System.out.print("Salary: ");
Salary=input.nextDouble();
Employee emp=new Employee(name,Salary);
em.persist(emp);
//Store emp into Database
}
em.getTransaction().commit();
System.out.println("n"+n+" employee record(s) Created!n");
TypedQuery count=em.createQuery(countQuery,Employee.class);
System.out.println("n"+count.getSingleResult()+" employee record(s) Available in Database!n");
}
/**
* Deletes the specified Employee from the database
*@param name
*/
private static void delete(String name)
{
em.getTransaction().begin();
Employee e=(Employee) em.find(Employee.class, name);
//Find Object to be deleted
em.remove(e);
//Delete the Employee from database
System.out.printf("Employee %s removed from Database....",e.name);
em.getTransaction().commit();
//Display Number of Employees left
TypedQuery count=em.createQuery(countQuery,Employee.class);
System.out.println("n"+count.getSingleResult()+" employee record(s) Available in Database!n");
}
/**
* Changes salary of the specified employee to passed salary
*@param name
*@param Salary
*/
private static void modify(String name,Double Salary)
{
em.getTransaction().begin();
Employee e=(Employee) em.find(Employee.class, name); //Find Employee to be modified
e.setSalary(Salary);
//Modify the salary
em.getTransaction().commit();
System.out.println("Modification Successful!n");
}
public static void main(String arg[])
{
System.out.println("Welcome to the Employee Database System!nn");
do{
System.out.print("Menu: n 1. View DBn2. Insert n3. Delete n4. Modifyn5. ExitnEnter Choice...");
int ch=input.nextInt();
try{
switch(ch)
{
case 1:
displayAll();
break;
case 2:
insert();
break;
case 3:
System.out.print("Name of Employee to be Deleted2: ");
name=bufferedReader.readLine();
delete(name);
break;
case 4:
System.out.print("Name of Employee to be Modified: ");
name=bufferedReader.readLine();
System.out.print("New Salary: ");
Salary=input.nextDouble();
modify(name,Salary);
break;
case 5:
if(em!=null) em.close();
/Close EntityManager
if(emf!=null) emf.close();
//Close EntityMana/gerFactory
exit=true;
break;
}
}
catch (IOException e)
{
e.printStackTrace();
}
}while(!exit);
}
static EntityManagerFactory
emf=Persistence.createEntityManagerFactory("codeDB.odb");
static EntityManager em=emf.createEntityManager();
static Scanner input=new Scanner(System.in);
static BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
static int n;
static String name;
static Double Salary;
static boolean exit=false;
static String countQuery="Select count(emp) from Employee emp";
static String displayAllQuery="Select emp from Employee emp";
}
This was an example of how to perform CRUD functionality in JPA.
How codersarts can help in JPA?
Codersarts provides
JPA assignment Help
JPA development Help
Error Resolving Help and Debugging Help
Mentorship in Java
If you are looking for any kind of help in java ,Contact us for instant Help.
Σχόλια