Monday, 3 September 2012

Spring Web JPA Hibernate In-Memory Example

This post introduces the web version of the Standalone Hibernate JPA In-Memory example. It relies on a very simple implementation of the Spring MVC framework. This example is available from Github in the Spring-Web-JPA-Roundtrip directory.


Instead of using the traditional JPA persistence.xml configuration file, we use Java configuration. On top of the traditional WebConfig class, we have a JpaConfig class annotated with @EnableTransactionManagement to enable database transactions.

The LocalContainerEntityManagerFactoryBean is the easiest mean to configure JPA. Notice that the persistence.xml database connection information is moved to the DataSource. The PlatformTransactionManager is required to process @Transactional annotated method (discussed further).

PersistenceExceptionTranslationPostProcessor converts any vendor specific exceptions into Spring DataAccessException for easier handling.
public class JpaConfig {

    public LocalContainerEntityManagerFactoryBean entityManagerFactoryBean(){

        LocalContainerEntityManagerFactoryBean lcemfb
            = new LocalContainerEntityManagerFactoryBean();

        lcemfb.setPackagesToScan(new String[] {"com.jverstry"} );

        HibernateJpaVendorAdapter va = new HibernateJpaVendorAdapter();

        Properties ps = new Properties();
        ps.put("hibernate.dialect", "org.hibernate.dialect.HSQLDialect");
        ps.put("", "create");


        return lcemfb;


    public DataSource dataSource(){

        DriverManagerDataSource ds = new DriverManagerDataSource();

        return ds;


    public PlatformTransactionManager transactionManager() {

        JpaTransactionManager tm = new JpaTransactionManager();

            this.entityManagerFactoryBean().getObject() );

        return tm;


    public PersistenceExceptionTranslationPostProcessor exceptionTranslation() {
        return new PersistenceExceptionTranslationPostProcessor();


Data Item, Controller & Repository

The persisted data relies on Pojomatic:
public class Item implements Serializable {

    private long ID;

    private String name = "";

    // Setter, Getters, Pojomatic methods...

The controller calls the injected repository class for a CRUD roundtrip, and retrieves the generated messages in the model:
public class MyController {

    private MyRepository rep;

    @RequestMapping(value = "/")
    public String home(Model model) {
        return "index";

    @RequestMapping(value = "/roundtrip")
    public String Roundtrip(Model model) {

        model.addAttribute("Messages", rep.performRoundtrip());

        return "roundtrip";


The repository annotated class, performs a CRUD (Create, Read, Update, Delete):
public class MyRepository {

    private EntityManager em;

    public List<String> performRoundtrip() {

        List<String> l = new ArrayList<String>();

        try {

            l.add("Before create");

            l.add("Before read I");

            l.add("Before update");

            l.add("Before read II");

            l.add("Before delete");

            l.add("Before read III");

        } catch (Exception ex) {



        return l;


    private Item i = null;

    public void create(List<String> l) {
        i = new Item();
        i.setName("Item A");
        l.add("- Before saving   : " + i);
        l.add("- After saving    : " + i);

    public void read(List<String> l) {
        Item retr = em.find(Item.class, this.i.getID());
        l.add("- Retrieved       : " + retr);

    public void update(List<String> l) {
        i.setName("Item B");
        l.add("- Updated         : " + i);

    public void delete(List<String> l) {
        l.add("- Deleting        : " + i);


JSP Page

The following roundtrip.jsp displays the messages collected during the roundtrip:
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="" %>
<!DOCTYPE html>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Roundtrip !!!</title>
        <c:forEach items="${Messages}" var="element">
            ${element}<br />
        </c:forEach><br />
        <a href="<c:url value='/'/>" />Home</a>

Running the example

Once compiled, the example can be run with mvn tomcat:run. Then, browse http://localhost:8585/spring-web-jpa-roundtrip/.

The generated output is:
Before create
 - Before saving : Item{ID: {0}, name: {Item A}}
 - After saving : Item{ID: {1}, name: {Item A}}
Before read I
 - Retrieved : Item{ID: {1}, name: {Item A}}
Before update
 - Updated : Item{ID: {1}, name: {Item B}}
Before read II
 - Retrieved : Item{ID: {1}, name: {Item B}}
Before delete
 - Deleting : Item{ID: {1}, name: {Item B}}
Before read III
 - Retrieved : null

More Spring related posts here.