Spring 3 MVC Hibernate H2 Embedded database Tutorial

In this tutorial we will create simple Spring 3 MVC application with H2 as embedded database. This configuration is useful for fast prototyping, especially during the development phase.

Technologies used:

  1. Spring 3.2.9.RELEASE
  2. JDK 1.6
  3. Maven 3
  4. Hibernate 4.3.5
  5. H2 database

1. Project setup

The basic project configuration for Spring MVC project is explained in previous post.
We should add the following dependencies to Maven pom.xml file:

<!-- Spring -->
  <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-context</artifactId>
   <version>${org.springframework-version}</version>
  </dependency>
  <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <version>${org.springframework-version}</version>
        </dependency>
  <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>${org.springframework-version}</version>
        </dependency>
  <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-webmvc</artifactId>
   <version>${org.springframework-version}</version>
  </dependency>
        <dependency>
           <groupId>org.springframework</groupId>
           <artifactId>spring-jdbc</artifactId>
           <version>${org.springframework-version}</version>
       </dependency>
       
       <!-- Hibernate -->
   <dependency>
      <groupId>org.hibernate</groupId>
      <artifactId>hibernate-core</artifactId>
      <version>${org.hibernate-version}</version>
  </dependency>
  <dependency>
   <groupId>org.hibernate</groupId>
   <artifactId>hibernate-entitymanager</artifactId>
   <version>${org.hibernate-version}</version>
  </dependency>
  
  <!-- H2 -->
  <dependency>
      <groupId>com.h2database</groupId>
      <artifactId>h2</artifactId>
      <version>1.3.165</version>
     </dependency>
    
  <!-- Servlet -->
  <dependency>
   <groupId>javax.servlet</groupId>
   <artifactId>servlet-api</artifactId>
   <version>2.5</version>
   <scope>provided</scope>
  </dependency>
  <dependency>
   <groupId>javax.servlet.jsp</groupId>
   <artifactId>jsp-api</artifactId>
   <version>2.1</version>
   <scope>provided</scope>
  </dependency>
  <dependency>
   <groupId>javax.servlet</groupId>
   <artifactId>jstl</artifactId>
   <version>1.2</version>
  </dependency>

2. Spring configuration

In web.xml we have to declare DispatcherServlet and ContextLoaderListener:

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
    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">

    <!-- The definition of the Root Spring Container shared by all Servlets and Filters -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/root-context.xml</param-value>
    </context-param>
    
    <!-- Creates the Spring Container shared by all Servlets and Filters -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <!-- Processes application requests -->
    <servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

</web-app>

The dispatcher-servlet.xml file should have the following content:

<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xmlns:beans="http://www.springframework.org/schema/beans"
 xmlns:context="http://www.springframework.org/schema/context"
 xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
  http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
  http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

 <!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure -->
 
 <!-- Enables the Spring MVC @Controller programming model -->
 <annotation-driven />

 <!-- Resolves views selected for rendering by @Controllers to .jsp resources in the /WEB-INF/views directory -->
 <beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
  <beans:property name="prefix" value="/WEB-INF/views/" />
  <beans:property name="suffix" value=".jsp" />
 </beans:bean>
 
 <context:component-scan base-package="com.devcases.usermanager.web" />
 
</beans:beans>

In the root-context.xml file there is configured embedde H2 database and Hibernate managing this database.
There is also configured web server for H2 database.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:jdbc="http://www.springframework.org/schema/jdbc"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
         http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc.xsd">

    
    <!-- Root Context: defines shared resources visible to all other web components -->
    
    <mvc:annotation-driven />
    
    <context:component-scan base-package="com.devcases.usermanager" />
    
    <mvc:resources mapping="/resources/**" location="/resources/" />
    
    <!-- Use in-memory embedded H2 database -->
    <jdbc:embedded-database id="dataSource" type="H2">
    </jdbc:embedded-database>
    
    <!-- Run H2 web server within application that will access the same in-memory database -->
    <bean id="h2Server" class="org.h2.tools.Server" factory-method="createTcpServer" init-method="start" destroy-method="stop" depends-on="h2WebServer">
        <constructor-arg value="-tcp,-tcpAllowOthers,-tcpPort,9092"/>
    </bean>
    <bean id="h2WebServer" class="org.h2.tools.Server" factory-method="createWebServer" init-method="start" destroy-method="stop">
        <constructor-arg value="-web,-webAllowOthers,-webPort,8082"/>
    </bean>
    
    <!-- Database managed by Hibernate -->
    <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <property name="persistenceUnitName" value="UsersPU" />
        <property name="dataSource" ref="dataSource" />
        <property name="packagesToScan" >
            <list>
                <value>com.devcases.usermanager.model</value>
            </list>
        </property>
        <property name="persistenceProvider">
            <bean class="org.hibernate.jpa.HibernatePersistenceProvider" />
        </property>
        <property name="jpaProperties">
            <map>
                <entry key="hibernate.dialect" value="org.hibernate.dialect.H2Dialect" />
                <entry key="hibernate.hbm2ddl.auto" value="create" />
                <entry key="hibernate.hbm2ddl.import_files" value="import_data.sql" />
                <entry key="hibernate.show_sql" value="true" />
            </map>
        </property>
    </bean>

    <bean id="transactionManager"
            class="org.springframework.orm.jpa.JpaTransactionManager">
        <property name="entityManagerFactory" ref="entityManagerFactory" />
    </bean>

    <tx:annotation-driven transaction-manager="transactionManager" />
        
</beans>

By setting ‘hibernate.hbm2ddl.import_files’ parameter we are using Hibernate to load initial data to our database. The contents of the ‘import_data.sql’ file are:

INSERT INTO public.user values (-1, 'john', 0);
INSERT INTO public.user values (-2, 'alex', 0);
INSERT INTO public.user values (-3, 'nick', 0);
INSERT INTO public.user values (-4, 'alan', 0);

In the above configuration we are also running H2 web server.

3. JSP View

the home.jsp file dispaying users list with actions: adding user and delete it:

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
    <head>
        <title>Home</title>
    </head>
<body>
    <h1>User management</h1>
    
    <table>
        <c:forEach var="user" items="${users}">
            <tr>
                <td>
                    <c:out value="${user.username}"/>
                </td>
                <td>
                    <a href="<c:url value="/delete/${user.id}"/>" >Delete user</a>
                </td>
            </tr>
        </c:forEach>
        <c:if test="${empty users}">
            no users added yet.
        </c:if>
    </table>
    
    <a href="<c:url value="/add"/>" >Add new user</a>
</body>
</html>

4. Deploy and run

Finally we can build project with maven:

mvn clean install

Generated war we can deploy on server (for example Tomcat)  and go to the url:

http://localhost:8080/HelloWorldApp/welcome

The example code you can download from here

Leave a Reply

Your email address will not be published. Required fields are marked *