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;

    @Table(name = "EMP")
    public class Employee {

    private long empId;

    private String empName;

    private String empJob;

    private long empSal;

    @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;
  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=""
    < contentType="text/html; charset=UTF-8" />
    import=",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" />
    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);
    session.setAttribute( "EmpList", ((DAO)wac.getBean("dao")).getData(pageNumber));
    String myUrl = "pagingEmp.jsp?page=" + nextPage;

    pageContext.setAttribute("myUrl", myUrl);
    <h2 align="center">Emp Table with Display tag</h2>
    <jsp:useBean id="EmpList" scope="session" type="java.util.List"></jsp:useBean>
    <th>Employee Id</th>
    <c:forEach items="${EmpList}" var="emp" begin="0" end="10">
    <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>

    <td colspan="2"></td>
    <td colspan="2"><a href="${pageScope.myUrl}">nextPage</a></td>
  3. The Application Context: The application context is shown below:
    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="" xmlns:xsi="" xsi:schemaLocation="">
    <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 id="entityManagerFactory"
    <property name="persistenceUnitName" value="myPersistenceUnit" />

    <property name="dataSource" ref="dataSource" />
    <property name="loadTimeWeaver">
    <bean class="org.springframework.instrument.classloading.glassfish.GlassFishLoadTimeWeaver"/>
    <property name="jpaDialect">
    <bean class="org.springframework.orm.jpa.vendor.TopLinkJpaDialect" />
    <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="" />

    <bean id="dao" class="data.DAO">
    <property name="entityManagerFactory" ref="entityManagerFactory" />
  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;

    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) {
    return result;
  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="" version="1.0">
    <persistence-unit name="myPersistenceUnit" transaction-type="RESOURCE_LOCAL"></persistence-unit>
  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="" version="2.5" xmlns:xsi=""

  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.


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

  2. have you tried this with Glassfish V2?


Popular Posts