Labels

.NET Job Questions About Java Absract class Abstract class Abstract Class and Interface Aggregation ajax aop apache ofbiz Apache ofbiz tutrial Association authentication autocad basics batch Binary Tree bootstrap loader in java build Builder design pattern C++ Job Questions caching CallableStatement in java certifications Chain of responsibility Design pattern charts check parentheses in a string Classes classloader in java classloading concept code quality collage level java program Composition concurrency Concurrency Tutorial Converting InputStream to String Core Java core java concept core java interview questions Core Java Interview Questions Core Java Questions core java tutorial CyclicBarrier in Java data structures database Database Job Questions datetime in c# DB Db2 SQL Replication deserialization in java Design Patterns designpatterns Downloads dtd Eclipse ejb example/sample code exception handling in core java file handling injava File I/O vs Memory-Mapped Filter first program in spring flex Garbage Collection Generics concept in java grails groovy and grails Guice Heap hibernate Hibernate Interview Questions how-to IBM DB2 IBM DB2 Tutorial ide immutable Interceptor Interface interview Interview Questions for Advanced JAVA investment bank j2ee java JAVA Code Examples Java 7 java changes java class loading JAVA Classes and Objects Java Classloader concept Java classloading concept java cloning concept java collection Java collection interview questions Java Collections java concurrency Java CountDownLatch java definiton Java design pattern Java EE 5 Java EE 6 Java Exceptions Java file Java Garbage Collection Java generics Java Glossary java hot concept java immutable concept Java Interface Java interview Question java interview question 2012 java interview question answer Java Interview Questions Java Interview Questions and Answers java interview topic java investment bank Java Job Questions java multithreading java multithreading concept java new features Java Packages java proxy object java questions Java Serialization Java serialization concept java serialization interview question java session concept java string Java Swings Questions java synchronization java threading Java Threads Questions java tutorial java util; java collections; java questions java volatile java volatile interview question Java Wrapper Classes java.java1.5 java.lang.ClassCastException JavaNotes javascript JAX-WS jdbc JDBC JDBC Database connection jdk 1.5 features JDK 1.5 new features Concurrent HashMap JMS interview question JMS tutorial job JSESSIONID concept JSESSIONID interview Question JSF jsp JSP Interview Question JSP taglib JSTL with JSP Junit Junit Concept Junit interview question.Best Practices to write JUnit test cases in Java JVM Linux - Unix tutorial Marker Interfaces MD5 encryption and decryption messaging MNC software java interview question musix NCR java interview question Networking Job Questions news Object Serialization Objects ojdbc14.jar OOP Oracle Oracle SQL Query for two timestamp difference orm own JavaScript function call in Apache ofbiz Packages Palm Apps patterns pdf persistence Portal Portlet Spring Integration Prime number test in java programs Rails Reboot remote computers REST Ruby Sample application schema SCJP security Senior java developer interviews servlet3 servlets session tracking singleton design pattern Spring Spring 2.5 Framework spring ebook Spring framework concept spring MVC spring pdf Spring Security Spring Security interview questions SQL SQL performance SQL Query to create xml file Sql Query tuning ssis and ssrs StAX and XML string concept string immutable string in java strings struts Struts2 Struts2 integration synchronization works in java Technical Interview testing tips Tomcat top Tutorial Volatile in deep Volatile working concept web Web Developer Job Questions web services weblogic Weblogic Application Server websphere what is JSESSIONID xml XML parsing in java XML with Java xslt


Friday, 19 July 2013

Data Access with Java Persistence API

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
  1. 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.

  2. You can download the Weblogic Application Server 10 TP from BEA.
Example Code
  1. Start with a "Dynamic Web Project" in Eclipse.
  2. 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.
  3. 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.
  4. 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.

  5. 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
  6. 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
  7. 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
  8. 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

No comments:

Post a Comment

LinkWithin

Related Posts Plugin for WordPress, Blogger...