JPA- Java Persistence API : Example
Packaging a persistence unit |
Packaging a persistence unit
The J2EE application consists of one or more entities. These entities are packaged in a persistence unit. In Simpler words, the entities are not limited to the EJB modules, rather, they are packaged in a web module, EAR module, or the standard jar file.
These entities are packaged in a descriptor called persistence.xml.
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="1.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd">
<persistence-unit name="persist123" transaction-type="JTA">
<provider>org.apache.openjpa.persistence.PersistenceProviderImpl</provider>
<jta-data-source>jta4anujcust</jta-data-source>
<mapping-file></mapping-file>
<jar-file></jar-file>
<class>javaskool.Customer</class>
</persistence-unit>
</persistence>
Obtaining an Entity Manager |
Obtaining an Entity Manager
- The Entity Manager in EJB 3.0 acts as a path for the client to acquire the entity manager services offered by EJB3.0 persistence framework. The Client sessions must have an entity manger instance for interacting with the entities. It helps in Querying, updating, removing, and refreshing the entity instances.
- Entity Manager maintains a collection of the instances within the transaction context called persistence context.
- The client can access or update the entity data as they would be the Plain Old Java Objects.
- The EntityManager can be obtained from both within the EJB Container or outside it.
- The Client can obtain an Entity Manager instance by using the Container Injection or by using the EntityManagerFactory or by looking up the EntityManger thru JNDI.
Obtaining an Entity Manager thru Session Bean Using the Container Injection
The session bean uses the container injection to obtain an EntityManager instance which is bound to a persistent unit.
@Stateless
Public class Customer
{
@PersitenceContext("persistence")
Private EntityManager em;
Public void createCustomer()
{
final Customer cust=new Customer();
cust.setName("abc");
em.persist(cust);
}
}
Obtaining an Entity Manager Using EntityManagerFactory
Sometimes the application desires more control over the life cycle of the Entity Manager. Then the client has a better option for obtaining the instance of an entity manger by an EntityManagerFactory. The javax.persistence.Persistence class acts as a factory to acquire the EntityManagerFactory.
public static void main(String a[])
{
final EntityManagerFactory emf=Persistence.createEntityManagerFactory("persistence");
final EntityManger em=emf.createEntityManager();
final Customer cust=new Customer();
cust.setName("abc");
em.persist(cust);
}
Obtaining an Entity Manager by looking up using JNDI
The EntityManagerFactory or the EntityManger, lookup with the help of the java Naming Directory Interface (JNDI).
EntityManger em=(EntityManager)ctx.lookup("xyz");
Different way to create EntityManager Object
- There are important differences between the injected EntityManager, and the EntityManager created from an injected EntityManagerFactory. Basically, injected EntityManager is container-managed, meaning all of its lifecycle is controlled by the container (web container or EJB container). Application code cannot close it, or otherwise interfere with its life.
- In addition, for a container-managed EntityManager, its associated PersistenceContext is automatically propagated along with the underlying JTA, from servlet A to servlet B, from servlet to EJB, from EJB a to EJB B, and so on. As such, EntityManager of the same configuration injected into various classes can share the same PersistenceContext in a call stack.
- On the other hand, EntityManager created from EntityManagerFactory is application-managed EntityManager. Application code is responsible for managing its whole lifecycle. And there is no PersistenceContext propagation for application-managed EntityManager.
- Are all EntityManager’s obtained from EntityManagerFactory application-managed EntityManager? Yes.
- Is it possible to get a container-managed EntityManager from EntityManagerFactory? No.
- You may have read about the method EntityManagerFactory.getEntityManager(), which returns a container-managed EntityManager. This method was considered and included in the early draft version of Java Persistence API, but was eventually removed from its final release.
Example for JPA |
Click Here to Download the Code
Java Persistence API ( JPA) without EJB Container mean application-managed only
META-INF/persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="1.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd">
<persistence-unit name="zzz" transaction-type="RESOURCE_LOCAL">
<!-- using default provider-->
<!--<provider>oracle.toplink.essentials.ejb.cmp3.EntityManagerFactoryProvider</provider>-->
<class>com.javaskool.Customer</class>
<properties>
<property name="toplink.jdbc.url" value="jdbc:mysql://localhost:3306/db1"/>
<property name="toplink.jdbc.user" value="root"/>
<property name="toplink.jdbc.driver" value="com.mysql.jdbc.Driver"/>
<property name="toplink.jdbc.password" value="admin"/>
<!--<property name="toplink.ddl-generation" value="drop-and-create-tables"/> -->
<property name="toplink.ddl-generation" value="create-tables"/>
<property name="toplink.jdbc.read-connections.max" value="1"/>
<property name="toplink.jdbc.read-connections.min" value="1"/>
<property name="toplink.jdbc.write-connections.max" value="1"/>
<property name="toplink.jdbc.write-connections.min" value="1"/>
</properties>
</persistence-unit>
</persistence>
Customer.java
package com.javaskool;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.NamedQuery;
import java.sql.Date;
@Entity
public class Customer
{
@Id
int customerId;
String name;
int age;
public void setCustomerId(int customerId) {
this.customerId = customerId;
}
public int getCustomerId() {
return this.customerId;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return this.name;
}
public void setAge(int age) {
this.age = age;
}
public int getAge() {
return this.age;
}
}
JPADemo1.java
package com.javaskool;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
import javax.persistence.Query;
import java.io.*;
public class JPADemo1
{
public static void main(String[] args)
{
EntityManagerFactory emf=Persistence.createEntityManagerFactory("zzz");
EntityManager em=emf.createEntityManager();
try
{
EntityTransaction et=em.getTransaction();
et.begin();
Customer cc=new Customer();
DataInputStream d=new DataInputStream(System.in);
System.out.println("Enter CID : ");
int cid=Integer.parseInt(d.readLine());
System.out.println("Enter Name: ");
String cname=d.readLine();
System.out.println("Enter Age : ");
int cage=Integer.parseInt(d.readLine());
cc.setCustomerId(cid);
cc.setName(cname);
cc.setAge(cage);
em.persist(cc);
et.commit();
Query query=em.createQuery("select c1 from Customer c1");
List rs=query.getResultList();
int size=rs.size();
System.out.println("CID \t Name \t Age" );
System.out.println("====\t =====\t ====");
for(int i=0;i<size;i++)
{
Customer c=(Customer)rs.get(i);
System.out.println(c.getCustomerId()+"\t"+c.getName()+"\t"+c.getAge());
}
}
catch(Exception e){System.out.println(e);}
finally
{
if(em != null){em.close();}
}
}
}
Recent Comments