Spring 3 has finally been released, a while back, with it’s all new features offering a better developer experience. But there hasn’t been any straight forward tutorial that could set you up on your path to roll out your application using dependency injection and web layer from Spring 3 and domain repositories through good old Hibernate. At least I couldn’t find such a helpful stuff which i could use as a stub for my next project rapidly.

There’s already a tool(actually a great code-generator “Spring Roo”) which brings up a Spring 3 based project within minutes but that doesn’t tell you how features from Spring 3 actually work. To learn that, let’s build our own project step by step.

This tutorial will be broken into three parts. By the end of this series it’ll have all the good stuff from Spring (that is Dependency Injection, MVC, Repository, Transaction demarcations, Aspects and all the fun) the Spring 3 way. We’ll be using Hibernate for relational persistence mapping.

In this Part(that is Part A) we will create a maven project first and make it talk to our database through Hibernate. So let’s start some coding by creating a maven project.

mvn archetype:create -DarchetypeArtifactId=maven-archetype-webapp -DgroupId=com.springhibernate.integration -DartifactId=spring-hibernate-webapp

Let’s get into our newly created “spring-hibernate-webapp” directory and make this baby work with Intellij Idea by executing

mvn idea:idea

Of course you can use any IDE of your choice. Anyways, after you see a “BUILD SUCCESSFUL” message on the command line, open this project into Intellij Idea. To make this project use Spring 3, Hibernate, Log4j, some Apache libraries and a couple of maven plugins etcetera we need to configure our pom.xml (since pom.xml is fairly long, i’ve avoided writing it’s content here. You can look at the source directly at google-code hosting of this project).

Let’s configure Hibernate for this project and march towards the end of this part of series.

  1. Under ‘src/main’ you should have a source folder named ‘java’ (if not then create it).
  2. Under that folder create a package ‘com.springhibernate.integration’.
  3. Create a class HibernateUtils.java under that package.
  4. At this point, to verify that all your maven dependencies are resolved and that your project setup is clean, you can create a main method inside inside HibernateUtils.java to print a greeting message like this.
    package com.springhibernate.integration;
    
    import com.springhibernate.integration.model.User;
    import org.hibernate.Session;
    import org.hibernate.SessionFactory;
    import org.hibernate.cfg.Configuration;</code>
    
    /**
    * @author Nabeel Ali Memon
    */
    public class HibernateUtils {
      public static void main(String[] args) {
        System.out.println("Working Correctly upto this point");
      }
    }
  5. To execute it, go to command line and run these maven commands:
    mvn compile
    mvn -e exec:java -Dexec.mainClass="com.springhibernate.integration.HibernateUtils"
    

    And you should successfully see “Working Correctly upto this point”.

  6. Now we need a relational database and a table to persist/retrieve our data. For all practical purposes, let’s use MySQL by creating a database, a table and one entry to that table as following.
    create database test;
    use test;
    create table user (
      user_id int(11) primary key,
      first_name varchar(30),
      last_name varchar(30),
      email varchar(30)
    );
    insert into user values
    (1, 'Nabeel', 'Memon', 'nabeelalimemon@gmail.com');
  7. We’r done with the database part. Let’s come back to our IDE and under the folder ‘src/resources’ create a new folder named ‘mappings’ and create a mapping file named ‘user.hbm.xml’ inside that folder. This mapping file should look like this:
    <?xml version="1.0"?>
    <!DOCTYPE hibernate-mapping PUBLIC
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
    
    <hibernate-mapping>
      <class name="com.springhibernate.integration.model.User" table="USER">
        <id name="id" column="USER_ID">
          <generator class="increment"/>
        </id>
        <property name="firstName" column="FIRST_NAME"/>
        <property name="lastName" column="LAST_NAME"/>
        <property name="email" column="EMAIL"/>
      </class>
    </hibernate-mapping>
    
  8. Under the package ‘src/main/java/com/springhibernate/integration’ create a package named ‘model’ and under that package create a class ‘User.java’ which is simply a Hibernate POJO for User entity.
    package com.springhibernate.integration.model;
    
    /**
    * @author Nabeel Ali Memon
    */
    public class User {
      private Long id;
      private String firstName;
      private String lastName;
      private String email;
    
      public User() { }
    
      public Long getId() {
        return id;
      }
    
      public void setId(Long id) {
        this.id = id;
      }
    
      public String getFirstName() {
        return firstName;
      }
    
      public void setFirstName(String firstName) {
        this.firstName = firstName;
      }
    
      public String getLastName() {
        return lastName;
      }
    
      public void setLastName(String lastName) {
        this.lastName = lastName;
      }
    
      public String getEmail() {
        return email;
      }
    
      public void setEmail(String email) {
        this.email = email;
      }
    }
  9. Hey we haven’t provided the hibernate configuration file yet, so let’s create one under ‘/src/resources’ named ‘hibernate.cfg.xml’
    <?xml version='1.0' encoding='utf-8'?>
    <!DOCTYPE hibernate-configuration PUBLIC
    "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
    "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
    
    <hibernate-configuration>
      <session-factory>
        <!-- Database connection settings -->
        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="connection.url">jdbc:mysql://localhost:3306/test</property>
        <property name="connection.username">username</property>
        <property name="connection.password">password</property>
        <property name="hibernate.format_sql">true</property>
        <!-- JDBC connection pool (use the built-in) -->
        <property name="connection.pool_size">1</property>
        <!-- SQL dialect -->
        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
        <!-- Enable Hibernate's automatic session context management -->
        <property name="current_session_context_class">thread</property>
        <!-- Disable the second-level cache  -->
        <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
        <!-- Echo all executed SQL to stdout -->
        <property name="hibernate.show_sql">true</property>
        <!-- Drop and re-create the database schema on startup -->
        <!--property name="hbm2ddl.auto">update</property-->
        <mapping resource="mappings/user.hbm.xml"/>
      </session-factory>
    </hibernate-configuration>
    
  10. So now let’s modify our ‘HibernateUtil.java’ exposing Hibernate Session Factory provider method(static) and get it to do some real stuff
    package com.springhibernate.integration;
    
    import com.springhibernate.integration.model.User;
    import org.hibernate.Session;
    import org.hibernate.SessionFactory;
    import org.hibernate.cfg.Configuration;
    
    /**
    * @author Nabeel Ali Memon
    */
    public class HibernateUtils {
      private static final SessionFactory sessionFactory = buildSessionFactory();
    
      private static SessionFactory buildSessionFactory() {
        try {
          // Create the SessionFactory from hibernate.cfg.xml
          return new Configuration().configure().buildSessionFactory();
        }
        catch (Throwable ex) {
          // Make sure you log the exception, as it might be swallowed
          System.err.println("Initial SessionFactory creation failed." + ex);
          throw new ExceptionInInitializerError(ex);
        }
      }
    
      public static SessionFactory getSessionFactory() {
        return sessionFactory;
      }
    
      public static void main(String[] args) {
        Session session = getSessionFactory().getCurrentSession();
        session.getTransaction().begin();
        User user = (User) session.get(User.class, new Long(1));
        System.out.println("user's email id is: "+user.getEmail());
        session.getTransaction().commit();
      }
    }

Simply execute the HibernateUtil.java file from (your IDE or) command line using maven exec plugin like we did before and you should see our user’s email address printed to screen.

That marks our project’s Hibernate usability. Hang on for the next part in which we actually configure Spring 3 in this project and introduce a Repository layer, Transactions and Logging Aspect being handled by Spring.

Update 1: Spring 3 integrated with Hibernate Part-B of this tutorial series is available now.
Update 2: I’ve hosted the entire project at code.google.com and have open sourced it under Apache 2 license. Enjoy!