The Java Persistence API simplifies the entity persistence model and adds new capabilities to the Java EE platform technology, it is the standard API for the management of persistence and object/relational mapping in Java EE 5. In this post, I will give a simple example of how to use JPA from a web application. I used BEA Kodo 4.1 and Weblogic application server 10.0 techinical preview. Follow these steps to run the example
- Download BEA Kodo 4.1 from here. You will also need to have a license file to use Kodo. The license file can be downloaded from here. Copy the license file into your classpath.
- You can download the Weblogic Application Server 10 TP from BEA.
Example Code- Start with a "Dynamic Web Project" in Eclipse.
- Create the Persistence Class (Entity): The source code for the entity class is shown below:
package beans;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "EMP")
public class Employee {
private long empId;
private String empName;
private String empJob;
private long empSal;
@Id
@Column(name = "EMPNO")
public long getEmpId() {
return empId;
}
public void setEmpId(long empId) {
this.empId = empId;
}
@Column(name = "JOB")
public String getEmpJob() {
return empJob;
}
public void setEmpJob(String empJob) {
this.empJob = empJob;
}
@Column(name = "ENAME")
public String getEmpName() {
return empName;
}
public void setEmpName(String empName) {
this.empName = empName;
}
@Column(name = "EMPSAL")
public long getEmpSal() {
return empSal;
}
public void setEmpSal(long empSal) {
this.empSal = empSal;
}
}
Employee.java- The persistence classes, or entities are annotated with the javax.persistence.Entity annotation.
- It is required to have a public/protected no-arg constructor.
- Neither Entity class nor any of it's properties are to be declared final.
- The @Id annotation defines a particular field as a primary key.
- The properties of the Entity class are mapped to the Columns of the database with the @Column annotation.
- Create the Data Access Object: The code for the Data access object is shown below
public class DAO {
private static int pageSize = 3;
private EntityManagerFactory emf;
private static DAO dao = new DAO();
private DAO() {
}
public static DAO getInstance() {
return dao;
}
public List getData(int pageNumber) {
EntityManager em = null;
try {
System.out.println(emf);
em = emf.createEntityManager();
Query query = em.createQuery("SELECT e FROM Employee e");
query = query.setFirstResult(pageSize * (pageNumber - 1));
query.setMaxResults(pageSize);
List results = query.getResultList();
return results;
} catch (Exception ex) {
ex.printStackTrace();
return null;
} finally {
em.close();
}
}
public void setEmf(EntityManagerFactory emf) {
dao.emf = emf;
}
}
DAO.java- The DAO class uses the EntityManagerFactory injected by the ContextListener on initialization, to obtain an instance of the EntityManager which is used to create Queries.
- Create a Context Listener: JPA annotations can be used to inject the EntityManager and the EntityManagerFactory into the Managed objects. The persistence annotations are supported only with managed classes such as servlet, filters, listeners, etc. You cannot use annotations with regular POJOs. To that end, I have created a Context Listener, which will be injected with the and which inturn injects the EntityManagerFactoryEntityManagerFactory into the DAO class.
public class ContextListener implements ServletContextListener {
@PersistenceUnit(unitName="emp")
EntityManagerFactory emf;
public void contextDestroyed(ServletContextEvent arg0) {
}
public void contextInitialized(ServletContextEvent arg0) {
// EntityManagerFactory emf = Persistence.createEntityManagerFactory ("emp");
DAO dao = DAO.getInstance();
System.out.println("EMF : " + emf);
dao.setEmf(emf);
}
}
ContextListener.java
The commented out line in the ContextListener class shown below EntityManagerFactory emf = Persistence.createEntityManagerFactory ("emp");
is another way to obtain an instance of the EntityManagerFactory.
- Update Web.xml: By default, when you create a "dynamic web project" in eclipse as of today, the web.xml file will be prepared for J2EE 1.4, you have to update it to Java EE5 (note the web-app declaration below). The application server will not inject the EntityManagerFactory into the ContextListener if the Web-App version is not set to 2.5, and you will get a NullPointerException. You also have to add the ContextListener to the web.xml file.
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
version="2.5"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<display-name>JPATest</display-name>
<listener>
<listener-class>listeners.ContextListener</listener-class>
</listener>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
web.xml - Create the JSP file: The JSP file here is similar to the previous JSP files used for the Paging examples. The only difference being the use of the DAO.getInstance() method. This change was made to be able to inject the EntityManagerFactory into the DAO object.
<jsp:root version="1.2" xmlns:jsp="http://java.sun.com/JSP/Page"
xmlns:c="urn:jsptld:http://java.sun.com/jsp/jstl/core">
<jsp:directive.page contentType="text/html; charset=UTF-8" />
<link rel="stylesheet" type="text/css" href="css/screen.css" />
<jsp:scriptlet>
int pageNumber=1;
if(request.getParameter("page") != null) {
session.setAttribute("page", request.getParameter("page"));
pageNumber = Integer.parseInt(request.getParameter("page"));
} else {
session.setAttribute("page", "1");
}
String nextPage = (pageNumber +1) + "";
session.setAttribute( "EmpList", data.DAO.getInstance().getData(pageNumber));
System.out.println(((java.util.List)session.getAttribute("EmpList")).size());
String myUrl = "pagingEmp.jsp?page=" + nextPage;
System.out.println(myUrl);
pageContext.setAttribute("myUrl", myUrl);
</jsp:scriptlet>
<h2 align="center">Emp Table with Display tag</h2>
<jsp:useBean id="EmpList" scope="session" type="java.util.List"></jsp:useBean>
<table>
<tr>
<th>Employee Id</th>
<th>Name</th>
<th>Job</th>
<th>Salary</th>
</tr>
<c:forEach items="${EmpList}" var="emp" begin="0" end="10">
<tr>
<td><c:out value="${emp.empId}"></c:out></td>
<td><c:out value="${emp.empName}"></c:out></td>
<td><c:out value="${emp.empJob}"></c:out></td>
<td><c:out value="${emp.empSal}"></c:out></td>
</tr>
</c:forEach>
<tr>
<td colspan="2"></td>
<td colspan="2"><a href="${pageScope.myUrl}">nextPage</a></td>
</tr>
</table>
</jsp:root>
pagingEmp.jsp - The persistence Unit definition: A persistence unit defines a set of entity classes managed by a single EntityManager. This set of entity classes represents the data contained within a single data store.
Persistence units are defined in the persistence.xml configuration file. The persistence.xml file is to be placed in the CLASSPATH/META-INF/ directory. Here is the persistence unit I defined in the example<?xml version="1.0" encoding="ISO-8859-1" ?>
<persistence 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"
version="1.0">
<persistence-unit name="emp" transaction-type="JTA">
<class>beans.Employee</class>
<properties>
<property name="kodo.ConnectionURL" value="jdbc:oracle:thin:@localhost:1521/orcl" />
<property name="kodo.ConnectionDriverName" value="oracle.jdbc.driver.OracleDriver" />
<property name="kodo.ConnectionUserName" value="scott" />
<property name="kodo.ConnectionPassword" value="tiger" />
<property name="kodo.jdbc.SynchronizeMappings" value="refresh" />
<property name="kodo.Log" value="DefaultLevel=WARN, SQL=WARN, Runtime=INFO, Tool=INFO" />
</properties>
</persistence-unit>
</persistence>
src/META-INF/persistence.xml - The Jar files: Make sure that you include the following JAR files from the KODO download
- serp.jar
- openjpa.jar
- ojdbc14.jar
- kodo.jar
- jta-spec1_0_1.jar
- jpa.jar
- jdo.jar
- commons-collections-3.2.jar
- commons-pool-1.3.jar
- commons-lang-2.1.jar
- jca1.0.jar
You will also need the jar files for JSTL etc...
Resources: This post described the implementation of JPA on Weblogic, here are a few resources that help you to implement JPA in different environments
It would be nice if the blog system used code indentation. The code here is quite unreadable. :(
ReplyDeleteDINF - oprogramowanie
In my persistence.xml I've specified the following properties in order for the container to manage transactions.
ReplyDeletepersistence-unit name="host" transaction-type="JTA">
property name="openjpa.ConnectionFactoryMode" value="managed"
property name="openjpa.TransactionMode" value="managed"
property name="openjpa.ManagedRuntime" value="jndi(TransactionManagerName=java:/TransactionManager)"
But when I try to access my DAO it says, You cannot access EntityTransactions while using managed transactions.
I'm not using any EJB's here. Can I delegate CMT to the container by specifying the above properties when using OpenJPA.
At the sametime, when I change the value to local, I've to explicitly call begin() & commit ()to manage the transactions.Any help on using container managed transactions will be of great help.
name="openjpa.TransactionMode" value="local"
Hi Abhi,
ReplyDeleteNice post. I developed internal training for BEA WLS 10 and Kodo 4.x. I just wanted to let you know that the Enterprise Edition of Kodo 4.1 comes embedded with WLS 10.0 so it does not require a separate download. You can find the OpenJPA libraries in the BEAHOME/modules folder. This was also true of the technology preview.
Hope this helps,
Mark
Hi Abhi,
ReplyDeleteI am getting a
java.lang.IllegalArgumentException: No persistence unit named 'emp' is available in scope JPA.war. Available persistence units: []
Any idea what this is about.
regards,
Ravi
There Are A Lot Of Forex Trading Websites Out There. It's Confusing To Keep Track Of Them With All Their Offers And Features. We Do The Research So You Don't Have To. At Live Forex Trading , We'll Tell You Exactly What You Need To Know So You Can Make An Informed Decision To Find The Right Forex Broker For Your Needs.
ReplyDelete