5 minutes with – Spring Jpa

In this post I’d like to show how use Spring with Java Persistence API. I think Jpa is a good standard framework and I’m using Hibernate implementation in the follow example.

Other resources are at official Spring guide (Chapter 14.5 JPA) and I suggest to take a look at wikipedia’s definition of Jpa (I’ve found that a lot of people have a little confusion about Jpa..).

First of all we have to annotate the bean that we’ll use to mapping the data.

package it.sample.data;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.Date;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
public class Order implements Serializable{
 private static final long serialVersionUID = 1L;
 private int orderId;
 private BigDecimal invoice;
 private int itemNumber;
 private Date orderDate;
 public Order(){}
 public Order(BigDecimal invoice,
    int itemNumber,
    Date orderDate){
  // String Representation:
    public String toString() {
        return "orderId: " + getOrderId() +
     " invoice: " + getInvoice().toString() +
     " itemNumber: " + getItemNumber() +
     " orderDate: " + getOrderDate().toString();
 public int getOrderId() {
  return orderId;
 public void setOrderId(int orderId) {
  this.orderId = orderId;
 public BigDecimal getInvoice() {
  return invoice;
 public void setInvoice(BigDecimal invoice) {
  this.invoice = invoice;
 public int getItemNumber() {
  return itemNumber;
 public void setItemNumber(int itemNumber) {
  this.itemNumber = itemNumber;
 public Date getOrderDate() {
  return orderDate;
 public void setOrderDate(Date orderDate) {
  this.orderDate = orderDate;

This class is the representation of the Order data table on derby DB.


Now we need to create a dao controller of this class

package it.sample.dao;
import it.sample.data.Order;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
public class OrderDao {
    private EntityManager em;
    // Stores a new Order:
    public void persist(Order order) {
    public List<Order> getAllOrders() {
        TypedQuery<Order> query = em.createQuery(
            "SELECT o FROM Order o", Order.class);
        return query.getResultList();
    // Get Id  
    public Order getFirstOrder(int id) {
     TypedQuery<Order> query = em.createQuery("SELECT o FROM Order o WHERE o.id=:id",Order.class);
     query.setParameter("id", id);
     List<Order> orders = query.getResultList();
     if (orders.size()>0)
      return orders.get(0);
      return new Order(new BigDecimal(0), 0, new Date());

On this class we can see EntityManager’s instance and three methods.
The first we’ll be used to insert data into the table. The second to get all orders and the last to get order by order Id.

The controller class accepts the requests from Url /order. It lets the user fill it the form and insert the data into db.

package it.sample.controller;
import java.math.BigDecimal;
import java.util.Date;
import it.sample.dao.OrderDao;
import it.sample.data.Order;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
public class OrderController {
    private OrderDao orderDao;
    public ModelAndView orderstore(HttpServletRequest request) {
     BigDecimal invoice = null;
     int itemNumber = 0;
     if ((request.getParameter("invoice")!=null) && (request.getParameter("itemNumber")!=null))
      invoice = BigDecimal.valueOf(Double.valueOf(request.getParameter("invoice")));
      itemNumber = Integer.valueOf(request.getParameter("itemNumber"));
        if (itemNumber != 0)
            orderDao.persist(new Order(invoice, itemNumber, new Date()));
        // Prepare the result view (guest.jsp):
        return new ModelAndView("order.jsp", "orderDao", orderDao);

The last file is the spring’s configuration.

   <!-- View resolver -->
	<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="/WEB-INF/"/>

  <!-- Add JPA support -->
	<bean id="emf" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
		<property name="persistenceUnitName" value="OrderPU"/>
		<property name="dataSource" ref="dataSource"/>
		<property name="jpaVendorAdapter">
			<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
				<property name="showSql" value="true"/>
				<property name="generateDdl" value="false"/>
				<property name="databasePlatform" value="org.hibernate.dialect.DerbyDialect"/>
		<property name="loadTimeWeaver">
			<bean class="org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver"/>

	<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
		<property name="driverClassName" value="org.apache.derby.jdbc.EmbeddedDriver"/>
		<property name="url" value="jdbc:derby:C:/eclipse-Mule3.0/workspace/SampleWebJpaSpring/derbyDB"/>
		<property name="username" value=""/>
		<property name="password" value=""/>

In this file it’s configured the datasource bean and Jpa support with hibernate. You can change these parts with other Jpa adapter and Db.

The persistence unit is configured in persistence.xml file under /META-INF folder.

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence"

  <persistence-unit name="OrderPU" transaction-type="RESOURCE_LOCAL">


Now we need a jps file for user interface.

<%@page contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%@page import="it.sample.controller.OrderController"%>
<%@page import="it.sample.dao.OrderDao"%>
<%@page import="it.sample.data.Order"%>

<jsp:useBean id="orderDao" type="it.sample.dao.OrderDao" scope="request" />

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"


        <form method="POST" action="order.html">
        	Invoice: <input type="text" name="invoice" />
            Items Number: <input type="text" name="itemNumber" />
            <input type="submit" value="Add" />

        <% for (Order order : orderDao.getAllOrders()) { %>
            <li>OrderId: <%= order.getOrderId() %><br>
            Items Number: <%= order.getItemNumber() %><br>
            Invoice: <%= order.getInvoice() %><br>
            Date: <%= order.getOrderDate() %><br>
        <% }
        int id = 1;
        First Element
        <%=orderDao.getFirstOrder(id) %>

This is the result page from tomcat.

I hope it can help somebody to order the ideas about integration between spring and Jpa.


I missed this important Tomcat configuration. When you start the web server remember to add this entry at the Virtual Machine arguments.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.