Introduction
We know that data is being a key role in applications life cycle, for example user registration process needs to store data and while login user has to be authenticated based on given data by comparing with the data stored in database (generally we are using DB server to store data). Here after performing user registration activity details about user has to be stored in a database, so here data must be persistent into some storage area ( may be like disk-storage, in memory storage etc...).We have different ways to persistent data in a computer, that is in a file system or in DBMS/RDBMS Systems( here iam not discussing about cache servers like Redis).
Data persistence means : simply writing data to file or database for future purpose.
Here we are disusing how data to be persistent in DB servers like MySQL from a java applications. JPA called as Java Persistence API for performing database related operations like storing, retrieving and updating. Before JPA we have JDBC to connect with DB server and then to perform CRUD operations.
JDBC vs JPA
JDBC is a low level package to connect with DB server directly to perform CRUD operations , where as JPA is standard for ORM (Object Relational Mapping). JDBC is executing native SQL queries and returns datasets, where as in JPA data base tables are representing with classes and rows of table with objects and table columns can be represented with class fields. POJO classes are used to representing with database tables. In fact JPA uses JDBC internally to perform database operations. Hibernate is one of the popular implementation framework of JPA. Hibernate called as ORM tool.
History of JPA
- First JPA version 1.0 released on 11th May 2006 as a part of EJB (JSR 220)
- JPA 2.0 was released on 10th December 2009 as an independent API from j2EE6.0 (JSR 317)
- JPA 2.1 was released on 22 April 2013 with Java EE 7
How JPA works?
JPA is one of the implementation of ORM. As i said Object is mapping with data of the table.In a database main keywords are table and fields of table. Entity class (POJO class) can be represented with data base table. So in JPA a program we must create entity classes for our database tables. javax.persistence is the package which contains all required classes and interfaces to implement JPA based java application. Following are list of classes and interfaces in JPA API
- Entity - This is useful to create a POJO class for a database table
- Entity Manager - EntityManger is an interface useful to create entity instances which will be identify by primary key of entity, and used to run queries on entities
- Query - is an interface used to control query execution
How to create Entity class
Now we will see that how to create a persistence entity class for database table, Let us consider we are going to create an entity class for given product database table.
product database table |
@Entity @Table(name = "product") public class Products { @Column(name = "productid") @Id @GeneratedValue(strategy = GenerationType.IDENTITY) Long pid; @Column(name = "productname") @NotNull @Size(max = 100) String pname; @Column(name = "productdesc") @NotNull @Size(max = 100) String pdesc; // add getter and setter methods here }In the above code our class is annotated with @Entity annotation, notice that our class name is Products and database table name is product so we need to use @Table annotation to set mapping between table and class (if names are not same). We can create an object for this entity whenever we want to perform database operations on product table. Entity class object has two states one is transient object and another one is persistent object.
Rules to create Entity class
Following are the rules to create Entity class in JPA
- Class must be annotated with @Entity annotation
- Class must not be final class
- Entity class must have zero argument constructor and also have other constructors
- Constructors must be either public or protected
- All fields must be private
- Must provide getter and setter methods for getting values and to set values
- If we want to pass Entity object as a value, Entity class must be serialisable class
Configuring persistent API
In persistence.xml file we can provide database connection url, database details along with database driver type. In this xml configuration file we can provide persistence unit name also.
<?xml version="1.0" encoding="UTF-8"?> <persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd"> <persistence-unit name="JPAnonej"> <class>com.nonej.entities.Products</class> <properties> <property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" /> <property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/nonej" /> <property name="javax.persistence.jdbc.user" value="yourUserNameForDB" /> <property name="javax.persistence.jdbc.password" value="yourPasswordForDB" /> </properties> </persistence-unit> </persistence>In the aobove code JPAnonej is a persistence unit name which will be used to create EntityManagerFactory reference.In line 6 we have used <class> tag to specify entity class(Products in our example) details along with complete path, we can specify more than one entity class by using multiple class tag. You can change other database related details as per your project.
Steps to perform JPA operations
We can perform database CRUD operations by using JPA by following bellow steps
1) First we need to create an object/reference to EntityManagerFactory by using Persistence class by providing persistence-unit name (JPAnonej is in our example) which given in persistence.xml file
EntityManagerFactory emf = Persistence.createEntityManagerFactory("JPAnonej");
2) Create an entity object (for Products class) on which we want to apply JPA operations on it
Products p= new Products(); p.setPname("Phone"); p..setPdesc("Mobile phone with camera");
3) Create an EntityManger object by using EntityManagerFactory object
/* Create EntityManager */ EntityManager em = emf.createEntityManager();
persist() method to save data into table
by using persist() method we can store entity object into database, but before that we need to begin transaction.
/* Persist entity ot store entity */ em.getTransaction().begin(); em.persist(p); em.getTransaction().commit();In the above code we have begin transartion for obtained transaction. After begining transaction we have invoked persist() method by passing value filled entity object p of Products class
find() method to get data from table
We can retrieve data from database table and then map table fields to database table ( Entity class ). To get data from data base table we can invoke find() method by padding .class file of entity class and primary key as a parameters.
/* Retrieve entity */ p = em.find(Products.class, 1); System.out.println(p);In the above code we are trying to get Product details where product id is 1 and notice that we have passed Products.class as a parameter to find() method, that means obtained data is of Products entity class type. Here p is called as Persistent object. Notice that to get data from database we are not begining transaction. That means to obtain data from data base table we no need to worry about transaction state.
Update in table
Now we will see how to do update of a row in a database table. Here we need to begin transaction and then at ending we need to commit transaction to confirm updates happening in database table.
/* Update entity */ em.getTransaction().begin(); p.setPname("New Phone"); System.out.println("Product after updation :- " + p); em.getTransaction().commit();You can notice theat there so no special method to update data of table, just begin transaction and set new values to entity by using setter methods, then do commit on transactions thats it update will be done in database.
Remove from table
We can remove data by using remove() method od EntityManger.
/* Remove entity */ em.getTransaction().begin(); em.remove(p); em.getTransaction().commit();This action also requires to start transaction and ends with commit.
Post a Comment
Post a Comment