Project Quickstart with Maven 2, Hibernate, Spring, JUnit and log4j

Dec 02, 2009
Jorge Tapia

First of all, I am one of those persons who prefers to learn from short specific tutorials and not with complex and useless books filled with useless details and situations that would almost NEVER happen in real life software engineering. The really important thing to keep in mind is to really make an effort to understand what every technology offers, why and in what way I can use it. We should NEVER become a recipe-following machine, I have sadly seen that through my years working in software development projects. This is completely avoidable if we seek good information sources and we try really hard to make everything we develop have real logic and real common sense.

The real purpose of this post is to provide a good starting point to develop a real-life application that integrates Maven2, Hibernate, Spring, JUnit and Log4j technologies and that any developer who is just getting into the matter can easily understand.

Project Creation using Maven 2:

Maven defines itself as a software project management and comprehension tool. It tackles many aspects of the development process. Firstly, one of the important points that we will ask Maven to help us with is to generate a simple project. To do this we type the following command at the command prompt or terminal:

mvn archetype:create -DarchetypeGroupId=org.apache.maven.archetypes -DgroupId=com.oshyn.example -DartifactId=example

Basically, what Maven does for us is create a directory structure and files for a simple project. There are many other archetypes for more complex projects. Our directory structure looks like this:

.
`-- example
|-- pom.xml
`-- src
    |-- main
    | `-- java
    |    `-- com
    |       `-- oshyn
    |          `-- example
    |             `-- App.java
    `-- test
       `-- java
          `-- com
             `-- oshyn
                `-- example
                   `-- AppTest.java

'

As our project grows and moves forward there will be more files, but this basic structure is what we need for this post purpose. There are two important parameters used in the previous command: groupId that is a text that allows us to give a hierarchical structure to our project, similar to what we do by assigning packages to our Java classes, and for that reason I highly recommend to keep the same naming convention. The other parameter is artifactId and it is usually bound to the project or module name.

As a comment, the main difference between Maven and ANT (another project building tool widely used for Java projects) is that Maven "knows" how to do certain tasks "by default" while ant requires some configuration even for the simplest project. A practically empty pom.xml file can compile, pack, generate javadoc and test a project only by following a few rules about our project directory structure.

The pom.xml file lets us set up our project building process. It is divided into different sections in which we can define certain properties that will be used later in other parts of our project. By the way, it is not my intention to explain what every tag in this file is. What I really want to stress is one of the most amazing Maven features: Dependency Resolution. A dependency is defined as one or many libraries or resources our project depends on. Under normal conditions we usually have to manually download and place these resources in our project. Maven offers us an easy way to access and get those dependencies, and to resolve the dependencies of our dependencies and the dependencies of the dependencies of our dependencies (I hope you get the idea).

We only have to define what "stuff" our project needs, and this is the way to do it:

<dependency>
  <groupId>org.hibernate</groupId>
  <artifactId>hibernate</artifactId>
  <version>3.2.6.ga</version>
</dependency>

The first questions many may be asking right now is "Where do we get all that information?" "I know I need Hibernate, but how do I know what groupId and artifactId I should use?" There are two answers for these questions. The first one: get an IDE with a very good Maven support (NetBeans 6.7.1 is just wonderful, because when filling the pom.xml file its code completion feature will suggest the correct values for those attributes automatically). The second answer is to visit mvnrepository.com and search by project name and use one of the suggested results.

We can talk A LOT about Maven. It has plugins that can virtually do everything we need. We can deploy our projects in almost any container, generate database schemas from our Hibernate Java classes or just create a site for our project. Creating a site does not even need ANY configuration so I find it worthy to mention. You just type the following on the command prompt or terminal and voila:

mvn site:site

Hibernate - Baby Steps:

The first thing we need to define is a class that maps a database entity. The "traditional" Hibernate way to do that was using POJOs (Plain Old Java Objects) and XML mapping files. Since JPA (Java Persistence API) exists, we can now use annotations as XML mapping files replacement. This is how a persistent entity class looks: Person.java

I must mention that this is not a JPA Annotations tutorial but I will explain the most important ones. @Entity tells Hibernate that our class maps a persistent entity (database entity/table); @Table, @Column and @Id lets us define the table name, column name and the primary key respectively. Of course we have annotations to define more complex stuff such as auto-incremental fields, nullables, many-to-many relationships, etc.

A very important point to stress is the equals() and hashcode() methods. For simple primary keys (not auto-generated) implementation is simple: use the id field value directly to resolve equality. If that is not the case then we MUST have a consistent business rule to compare objects. On the other hand, the hashcode() method has to fulfill a simple condition: if equals() then return true, then the hashcodes must be the same. There is no other condition that must be fulfilled. There is plenty of literature on how to efficiently write this method. My recommendation: write a hashcode() method that uses the same members used in the equals() method or use HashCodeBuilder and EqualsBuilder from Apache commons-lang.

Basic DAO implementation:

The DAO (Data Access Object) design pattern lets us separate the mechanisms from which we access data, from the data source itself. From experience I can tell that this is not extraordinarily common but another good argument to use the DAO pattern is the possibility to test our business logic without a data source (creating mock implementations of our DAOs for our services). In simple words, a DAO is an interface with the basic CRUD operations over our entity objects. In our example it looks like this:

package com.oshyn.example.dao;

import com.oshyn.example.model.Person;
import java.util.List;

public interface PersonDao {
  public void saveOrUpdate(Person person);
  public void delete(Person person);
  public void find(int id);
  public List<Person> findAllPersons();
}


Even if it is possible for us to implement this DAO for Hibernate manually, Spring framework provides us a wonderful class called HibernateDAOSupport that encapsulates most of the work we have to do to integrate both frameworks: HibernatePersonDao.java

The first thing to notice here is the presence of three new annotations. @Service tells Spring that this class should be named "personDAO" for it to be instantiated automatically by the framework every time we use the "personDAO" identifier. This can be done either by dependency injection or an explicit call of the contextToSpring.getBean("personDAO") method. For those familiar with Spring we are just replacing the following entry with an annotation in the spring-context.xml file:

<bean name="personDAO" class="com.oshyn.example.dao.HibernatePersonDao">
  <property name="sessionFactory" ref="sessionFactory" />
</bean>

The @Autowired annotation lets us tell Spring that the declared constructor requires a dependency injection, and in this case we need to inject Hibernate's SessionFactory object. How does Spring know where to inject the object and what to put in it? The @Qualifier annotation preceding the constructor parameter indicates where the dependency should be injected, while the annotation value tells the name of the object that Spring must inject.

Services and/or Managers:

We have so far the persistence objects and basic operations. The next step is to create a place where our business logic will be written and another place where we can declare all the transactions needed in our application (CRUD operations grouped into the same commit/rollback block). Spring documentation names these objects as "Service" but they are also known as "Manager". In our example the interface that defines our service is:

package com.oshyn.example.service;

import com.oshyn.example.model.Person;
import java.util.List;

public interface PersonManager {
  public void insertPersons(List<Person> persons);
  public List<Person> findAllPersons();
}

And the Spring annotations implementation looks like this: PersonManagerImpl.java

Two new annotations appear here. @Resource tells Spring to look for the "personDAO" resource and to inject it into my object (shortcut for @Autowired and @Qualifier but in a single line). The other annotation we find is @Transactional and this annotation lets us define a method or class that groups various operations that need a commit or a rollback.

Basic Spring Configuration:

Basically this is done by filling the spring-context.xml file. The most important points to mention are the following:

<!-- We tell Spring that we are using annotations -->
<context:annotation-config/>


<!-- Classes that should be scanned to look for resources -->
<context:component-scan base-package="com.oshyn.example" />


Let's define beans using @Service and dependency injection with @Autowired and @Qualifier.


<!-- Transaction support via annotations -->
<tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true" />


Let's define transactions using @Transactional inside a method.

Testing our Application:

A good way to see our code working is to get used to the JUnit framework (or any other unit testing framework such as TestNG). In this example we will test inserting two persons and then retrieving them, here is our test class: PersonManagerTest.java

The @Test annotation tells JUnit that this method should be executed when testing our project. Additionally the framework provides
a set of assertions to validate success or failure of our tests. In this example I just wanted to assert if the inserted persons are in the list retrieved from the database (using the contains() method from Collection).

Two more things to conclude:

1) SpringContext - this is a helper class that lets us access Spring beans throughout my application code. It is a very simple singleton and looks like this: SpringContext.java

2) We need a log4j configuration file log4j.properties (Our logging framework):

log4j.appender.NULL_APPENDER=org.apache.log4j.varia.NullAppender
log4j.rootLogger=FATAL, NULL_APPENDER
log4j.appender.DEBUG_APPENDER=org.apache.log4j.RollingFileAppender
log4j.appender.DEBUG_APPENDER.layout=org.apache.log4j.PatternLayout
log4j.appender.DEBUG_APPENDER.layout.ConversionPattern=[%-5p %d{dd/MM/yyyy hh:mm:ss,SSS}] %l - %m%n
log4j.appender.DEBUG_APPENDER.ImmediateFlush=true
log4j.appender.DEBUG_APPENDER.File=/tmp/debug_springExample.log
log4j.appender.DEBUG_APPENDER.Append=true
log4j.appender.DEBUG_APPENDER.Threshold=DEBUG
log4j.appender.DEBUG_APPENDER.MaxFileSize=10000KB
log4j.appender.DEBUG_APPENDER.MaxBackupIndex=10

Conclusions:

You now know the basics on how to build an application project using Maven2, Hibernate, Spring, JUnit and log4j.

You may do some additional research to gain deeper knowledge about the technologies used and what you can be able to create with them.

This tutorial was built using MySQL database server which must be configured, see the project source files. The complete source code project can be downloaded here: springExample.zip. You must build the project using Maven with the command mvn install and generate and IDE project using Maven plugins. To generate an Eclipse project use the command: mvn eclipse:eclipse