Oshyn Home Page
  • expertise
    • Overview
    • Contact Us |
    • Latest work: www.miramax.com
  • solutions
    • Overview
    • Content Management
      • Common Issues
      • Choosing a CMS
      • Training
      • Drupal Development
      • Jahia Integration
      • Sitecore Consulting
      • Open Text Web Solutions RedDot CMS
      • EPiServer CMS Consulting
    • E-commerce
    • SOA
    • Portals & Collaboration
    • Web Strategy
    • Mobile Platforms
    • Social Media
    • Contact Us |
    • Latest work: www.miramax.com
  • work
    • Overview
    • Client Quotes
    • Contact Us |
    • Latest work: www.websense.com
  • resources
    • Overview
    • News & Events
    • Newsletters
    • Blog
    • White Papers
    • Success Stories
    • Press Kit
    • Contact Us |
    • Latest work: www.disneydvd.com
  • partners
    • Overview
    • Agency Partner Program
    • Technology Partners
    • Contact Us |
    • Latest work: www.nea.org
  • company
    • Overview
    • Contact
    • Careers
    • Leadership Team
    • News & Events
    • Social Responsibility
    • Contact Us |
    • Latest work: www.icon4x4.com
Project Quickstart with Maven 2, Hibernate, Spring, JUnit and log4j
  • Tweet
Tuesday, October 20, 2009  /   Jorge Tapia Jorge Tapia
close

Jorge Tapia


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

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 http://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" />

Lets us 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" />

Lets us 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

Apache Maven2
http://maven.apache.org/

Spring Framework
http://www.springsource.org/

JBoss Hibernate
http://www.hibernate.org/

Apache log4j
http://logging.apache.org/log4j/

JUnit Test Framework
http://www.junit.org/

  • Share
  • Facebook    0
  • Twitter    0
Trackback Link
http://www.oshyn.com/BlogRetrieve.aspx?BlogID=2583&PostID=93379&A=Trackback
Trackbacks
Post has no trackbacks.

blog comments powered by Disqus

Pages: Previous Next

TwitterFacebookLinkedIn

Blog Authors

Christian Burne Christian Burne
question button image

 



Captcha Image

question button image
Subscribe Subscribe Subscribe Subscribe Subscribe
OTHER CATEGORIES
  • ALL

  • General

  • Web Content Management

  • Sitecore CMS

  • Open Text

  • Jahia

  • Drupal

  • EpiServer

  • SOA

  • Social Media and Mobile

  • Software Development

  • Visit Bloggers Profiles

RELATED POSTS
  • Jira new plugin: Bonfire for Agile Testing
  • Google App Inventor: An Android Mobile App Developer for Everyone
  • Agile Testing and Test Management
  • .Net Source Code Quality Tools – Part 3: Analyzing Code
  • Using WMDRM on your Application – Part 2
  • .Net Source Code Quality Tools – Part 2: Configuring the Build
  • Using WMDRM on your Application – Part 1
  • .Net Source Code Quality Tools – Part 1: Setup
  • ClickOnce Deployment - Creating a Custom Installer
  • Build Automation for Windows Presentation Framework (WPF) and Silverlight Applications

WHITE PAPERS
    ajax rotator

    Web Content Management, Social Media, Content: Three Kings for Your Website Web Content Management, Social Media, Content: Three Kings for Your Website (846 KB)
    Companies pursuing online marketing success, including Social Media, can increase the power of their online presence with right strategy and technology to maximize online visibility and engagement. Download this FREE white paper on the WCM, Social Media, and Content triad.

    Drupal Performance Tuning Drupal Performance Tuning (1213 KB)
    In this Free White Paper Oshyn evaluates Drupal Performance Tuning, sharing the results of testing response time and Requests Per Second (RPS) that a server can hold before the response rate becomes unacceptable. In this paper you will learn about optimizing performance of a website through changes to settings and the server.

    Enterprise Drupal: Social Media, Mobile, and Rich Media in your Website Enterprise Drupal: Social Media, Mobile, and Rich Media in your Website (1015 KB)
    In this free WCM white paper, Oshyn examines advanced Drupal capabilities: Multisite Environment, Access Control and Security, Enhanced User Profiles, Custom Breadcrumbs, Mobile Support, Podcasts, Advanced Multimedia, Locations and Maps, Internationalization and Locale based content, Events and Scheduled Tasks, Rules Actions and E-Commerce Solutions.

    Drupal Multilingual Drupal Multilingual (636 KB)
    There are several multilingual installation methods for Drupal. In this free white paper Oshyn evaluates and recommends several methods of using Drupal Open Source CMS to manage websites in multiple languages.

    Drupal Social Media Drupal Social Media (1297 KB)
    Looking for an Open Source CMS to for “Social Media Optimization” of your website? Download this free white paper, “Drupal and Social Media”, to learn about the extensive Social Media this Open Source CMS offers to create a dynamic and engaging website and online community.

    Drupal Multisite Options Drupal Multisite Options (427 KB)
    There are several multisite installation methods for Drupal. In this free white paper Oshyn evaluates and recommends several methods of using Drupal Open Source CMS to manage multiple sites.

    Open Source CMS: Is It Right for your Organization Open Source CMS: Is It Right for your Organization (496 KB)
    In this free white paper, “Open Source CMS: Is It Right for your Organization?” we share an in-depth look at the pros and cons of using Open Source Content Management Systems (CMS) or Open Source Web Content Management (WCM) platforms. Oshyn helps clients select CMS/WCM solutions based on the specific requirements of each client.

    Affiliate Content Sharing in a CMS/WCM World Affiliate Content Sharing in a CMS/WCM World (273 KB)
    The Content Editors at your company have created GREAT content! Now how do you share it? In this Free white paper learn several methods for using a Content Syndication tool to automatically repurpose content and how Content Sharing can generate business value.

    Sitecore and Social Media - An Interactive Web Content Management Platform Sitecore and Social Media - An Interactive Web Content Management Platform (898 KB)
    Social Media has revolutionized how people interact with business. In this white paper Oshyn’s Lead Sitecore Developer, Prasanth Nittala, discusses key points from the perspectives of marketing and Web development that make Sitecore a compelling choice for engaging in Social Media via your website. This Sitecore white paper draws from Oshyn’s expertise as a certified Sitecore partner, helping organizations understand the distinct capabilities offered by Sitecore CMS.

    The Business Case for Leveraging Open Text Web Solutions Delivery Manager The Business Case for Leveraging Open Text Web Solutions Delivery Manager (451 KB)
    This free white paper explores the evolving needs of small and medium size businesses and explains how the Open Text Web Solutions Delivery Manager (formerly RedDot LiveServer) can help businesses build their brand, reputation, and client base. This white paper examines strategies, key points and tips to leverage the features available in Open Text Web Solutions (RedDot CMS) to achieve an impactful user experience and to maximize visitor engagement through a reliable and powerful implementation.

    Open Text Best Practices: Part One Open Text Best Practices: Part One (763 KB)
    Authored by Oshyn Senior Consultant, Adaeze Okorie, this free CMS white paper draws from Oshyn’s vast experience as an Open Text Certified Partner, in helping organizations define strategies to meet business goals while implementing Open Text Web Solutions (RedDot CMS). Specifically in this free white paper Adaeze Okorie discusses strategies, key points and tips to leverage the features available in Open Text Web Solutions (RedDot CMS) to achieve an effective, reliable and robust implementation.

    Improving the ROI of Business Software: Service Oriented Architecture from a Business Perspective Improving the ROI of Business Software: Service Oriented Architecture from a Business Perspective (398 KB)
    Software selection and technology decision making should no longer be left to the IT department alone. By gaining an understanding of Service-Oriented Architecture, business people outside of the IT department will be better positioned to maximize the ROI of the company's technology platforms. Download this free white paper to learn more.

    Getting Over Social Media Marketing Paralysis for B2B Getting Over Social Media Marketing Paralysis for B2B (2254 KB)
    Many companies are well aware that Social Media has become critically important to engaging audiences and promoting online "presence" while some wonder how to approach their C-level executives and prove that it is not all hype. With so many ways to engage in Social Media, how can they get buy-in and begin execution with so many different venues and tools available? Staying on the sidelines and becoming a latecomer might make it more difficult to create a convincing "social" presence. Put the ove

    Performance Tuning Open Text Web Solutions Management Server and Delivery Server Performance Tuning Open Text Web Solutions Management Server and Delivery Server (235 KB)
    If you've made an investment in Open Text Web Solutions (formerly RedDot) Web Content Management products, you’ve undoubtedly experienced performance issues. While every CMS requires tuning, Open Text Web Solutions - RedDot is especially susceptible to mis-configuration and poor performance as the out-of-the-box installation comes untuned and ready for Development Environments only. In this FREE white paper we share performance tuning expertise as an Open Text Certified Partner that has optimize

    The Business Case for Leveraging Open Text Web Solutions Within Higher Education The Business Case for Leveraging Open Text Web Solutions Within Higher Education (430 KB)
    Academic institutions have a long reputation for being slower to adopt new technologies for their audiences. However, many schools are taking serious steps in improving the online experience they are providing. This white paper explores the unique needs of the higher education market, applying new tools & trends and specifically how the Open Text Web Solutions’ Delivery Manager (formerly known as RedDot LiveServer) can be leveraged to achieve those goals.

    SEO Best Practices within a Content Management System SEO Best Practices within a Content Management System (712 KB)
    In this free white paper, we share Search Engine Optimization (SEO) tips and best practices to follow when implementing a Content Management System (CMS). Certain features and functionality will help your content editors make website changes faster while minimizing the risk of human error. Download this free white paper to learn strategies to improve search engine rankings.

    Best Practices for Sitecore CMS Best Practices for Sitecore CMS (1121 KB)
    Sitecore CMS is an extensive Web Content Management (WCM) platform for the mid-market. It offers reduced IT expenditures, a streamlined content lifecycle, and a return of content control to the subject matter experts. The newest incarnation of Sitecore CMS version 6.0 is a mature product that incorporates standard social media components such as wikis, blogs, RSS syndication and “e-mail a friend” features.

    Optimizing SEO in your CMS (WCM) Optimizing SEO in your CMS (WCM) (3108 KB)
    Oshyn's Christian Burne spoke in depth about SEO in CMS at the Gilbane San Francisco Conference on June 3rd, 2009. Christian discussed the pressues of keyword competition and how the CMS can add tremendous power to climbing Google SERPs and other search engine rankings. The presentation was later part of a featured article on CMSWire. We've made the presentation available in PDF format. Download now to learn more about strategies for using your CMS to optimize SEO.

    The Best CMS for You: Tips on How to Select Your Next CMS The Best CMS for You: Tips on How to Select Your Next CMS (909 KB)
    As websites continue to grow in size, features and functionality, the visitors to these websites are also becoming more demanding and have higher expectations than ever before. Companies who committed valuable time and resources to web strategies just five years ago are finding they must re-evaluate and explore new options as their content, features and online offerings must keep pace with the constant and rapid movement in the digital marketplace. For many of these companies, there is a strong.

    Oshyn Sample Voluntary Product Accessibility Template (VPAT) Oshyn Sample Voluntary Product Accessibility Template (VPAT) (741 KB)
    Section 508 requires that when federal government and agencies procure, develop, and maintain or use electronic and information technology (EIT), they must ensure that it is accessible and in compliance with Section 508 standards developed by the Architectural and Transportation Barriers Compliance Board (Access Board). Oshyn understands these requirements and has delivered reports like these countless times.

    Sitecore CMS Implementation Best Practices Sitecore CMS Implementation Best Practices (481 KB)

    TwitterFacebookLinkedInAlltopFeatured in Alltop
    Oshyn, Inc.17785 Center Court Drive N Cerritos, CA 90703    1.888.483.1770 newbusiness@oshyn.com
    2012 Copyright Oshyn. All rights reserved.
    • View Mobile Version
    • Terms of Use
    • Privacy Policy
    • Contact Us