Wednesday, December 27, 2006

Data Access with Spring and JPA

The JDBC abstraction layer of Spring framework offers an understandable exception hierarchy, simplifies error handling, and greatly reduces the amount of code you'll need to write. Spring 2.0 has support for using JPA in the Data Access Layer. In this post, I will describe a step-by-step approach to implementing a Web Application that uses Spring 2.0 and Java Persistence API for Data Access. The example is the same one that I used in the previous persistence examples. This example is implemented using Spring 2.0 on Glassfish.
  1. The Entity Class: The Entity class is the Employee class 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
  2. The JSP page: The JSP page is also the same as used previously and is shown below.
    <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" />
    <jsp:directive.page
    import="org.springframework.web.context.support.XmlWebApplicationContext,org.springframework.beans.BeanUtils,org.springframework.web.context.ConfigurableWebApplicationContext, org.springframework.beans.factory.BeanFactory, data.DAO" />
    <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) + "";
    ConfigurableWebApplicationContext wac =
    (ConfigurableWebApplicationContext) BeanUtils.instantiateClass(XmlWebApplicationContext.class);
    wac.setServletContext(this.getServletContext());
    wac.refresh();
    session.setAttribute( "EmpList", ((DAO)wac.getBean("dao")).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
  3. The Application Context: The application context is shown below:
    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName" value ="oracle.jdbc.driver.OracleDriver" />
    <property name="url" value="jdbc:oracle:thin:@localhost:1521/orcl" />
    <property name="username" value="scott" />
    <property name="password" value="tiger" />
    </bean>
    <bean id="entityManagerFactory"
    class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
    <property name="persistenceUnitName" value="myPersistenceUnit" />

    <property name="dataSource" ref="dataSource" />
    <property name="loadTimeWeaver">
    <bean class="org.springframework.instrument.classloading.glassfish.GlassFishLoadTimeWeaver"/>
    </property>
    <property name="jpaDialect">
    <bean class="org.springframework.orm.jpa.vendor.TopLinkJpaDialect" />
    </property>
    <property name="jpaVendorAdapter">
    <bean class="org.springframework.orm.jpa.vendor.TopLinkJpaVendorAdapter">
    <property name="showSql" value="true" />
    <property name="generateDdl" value="false" />
    <property name="databasePlatform" value="oracle.toplink.essentials.platform.database.oracle.OraclePlatform" />
    </bean>
    </property>
    </bean>

    <bean id="dao" class="data.DAO">
    <property name="entityManagerFactory" ref="entityManagerFactory" />
    </bean>
    </beans>
    WEB-INF/applicationContext.xml
  4. The Data Access Object: The data access object extends the JpaDaoSupport. JpaDaoSupport like JdbcTemplate implements most of the boiler-plate code for implementing JPA data access.
    package data;

    import java.util.List;

    import org.springframework.orm.jpa.JpaTemplate;
    import org.springframework.orm.jpa.support.JpaDaoSupport;

    public class DAO extends JpaDaoSupport {
    public long empId;
    public String empName;
    public String empJob;
    public long empSal;

    public List getData(long minSal) {
    JpaTemplate daoTmplt = getJpaTemplate();
    System.out.println("Creating query.");
    List result = null;
    try {
    result = daoTmplt.find("select e from Employee e");
    }catch(Throwable e) {
    e.printStackTrace();
    }
    return result;
    }
    }
    DAO.java
  5. The persistence xml: The persistence XML file does not have any persistence description as used in the JPA post. This is because it is defined in the application context XML file.
    <persistence xmlns="http://java.sun.com/xml/ns/persistence" version="1.0">
    <persistence-unit name="myPersistenceUnit" transaction-type="RESOURCE_LOCAL"></persistence-unit>
    </persistence>
    src/META-INF/persistence.xml
  6. The Web Deployment Descritor: The web deployment descriptor is shown below. Note the listener definition for org.springframework.web.context.ContextLoaderListener.
    <?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>SpringJpa</display-name>
    <context-param>
    <param-name>log4jConfigLocation</param-name>
    <param-value>/WEB-INF/log4j.xml</param-value>
    </context-param>
    <listener>
    <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
    </listener>

    <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>default.jsp</welcome-file>
    </welcome-file-list>
    </web-app>
    web.xml
  7. Setup: In order to run the example on Glassfish, you have to create an EAR and install the EAR instead of trying to deploy a WAR file on Glassfish. Deploying WAR files gives some classloading related exceptions. The reason is, as yet, unknown to me. Hope to find out soon.

2 comments:

  1. Hi Abhi - WHich version of GlassFish did you use? Have you already asked the USERS @ glassfish.dev.java.net mailing list? - eduard/o

    ReplyDelete
  2. have you tried this with Glassfish V2?

    ReplyDelete