Welcome!

Java Authors: Maureen O'Gara, Bruce Armstrong, Liz McMillan, Walter H. Pinson, III, Yakov Werde

Related Topics: Java

Java: Article

Java J2EE Hibernate Extreme Makeover: Architecture Edition

Large-scale refactoring with Spring and Hibernate

One of the things that Spring excels at is being an IOC container. Spring uses a declarative approach to move an object's dependencies into an XML configuration file.

<!-- Spring wired Business Service bean -->
<bean id="businessServiceTarget" class="example.BusinessServiceImpl">
   <property name="provisionWebService">
   <ref bean="provisionWebService"/></property>
   <property name="orderDAO"><ref bean="orderDAO"/></property>
</bean>

This example shows how a POJO business service class would be defined in a Spring configuration file. This bean is injected with two other beans called provisionWebService and orderDAO. The injected provisionWebService bean implements the interface ProvisionIF. By having public getter() and setter() methods on our business service we can literally change the implementation of the provisionWebService attribute at runtime. As long as we inject another class that implements the ProvisionIF interface our business service bean will be content. This same pattern would apply to the order data access object (DAO) injected bean.

public class BusinessServiceImpl implements BusinessServiceIF {
   private ProvisionIF provisionWebService;
   public ProvisionIF getProvisionWebService();
   public void setProvisionWebService(ProvisionIF provisionWebService);

   private OrderDAOIF orderDAO;
   public OrderDAOIF getOrderDAO();
   public void setOrderDAO(OrderDAOIF orderDAO);

}

Unit testing our business service class just got a lot easier. Now we don't have to rely on the provisioning Web Service to be available for testing. We can use Spring to inject a stub class that implements the ProvisionIF interface and returns canned data. This class has to be a concrete implementation and physically present as a Java class. If we don't want a proliferation of stub classes we can always choose a mocking framework like EasyMock. EasyMock provides mock objects for interfaces and generates them on-the-fly using Java's dynamic proxy mechanism. Tools like dependency injection and mock objects are a perfect fit for TDD since application code should be written so that modules are testable in isolation. These two paradigms for testing are shown graphically in Figure 2.

We have unit-tested our code, but how do we capture live metrics data in a production environment without writing copious amounts of auditing logic? SOA has enabled distributed architectures, but with that comes the headache of uniformly capturing input/output data, storing error messages, measuring request/response times, and correlating message calls. AOP aids developers in handling cross-cutting concerns such as security, auditing, logging, and transaction management. An 'advice' in Spring is an action taken by the AOP framework at a particular point during the execution of a program. The most typical types of 'advice' used in Spring are "around," "before," "after," and "throws." Spring has modeled these types as interceptors that are done using a chaining mechanism. Spring lets you attach N number of interceptors to a wired bean. In the example in Listing 1 we've attached an "around" audit interceptor to our bean that performs actions before and after the method invocation. This interceptor is applied declaratively. Spring uses dynamic proxies for AOP proxies but can also use CGLIB proxies if it's necessary to proxy a class rather than an interface.

Our example shows our business service bean dynamically proxied with a custom audit interceptor and a Hibernate interceptor provided by Spring. The audit interceptor is just another Spring wired bean that implements a MethodInterceptor interface. The audit interceptor will insert audit information into an auditing database before and after our business service method is invoked. This auditing information is now an integral part of capturing application metrics and managers distribute reports on a daily basis. The Hibernate interceptor is a class provided by Spring that handles Hibernate session management.

It's Dozerin' Time
Symptom: Proliferation of Java Bean mapping classes
Root Cause: Need for transformation between internal do main objects to external Web Service calls
Solution: Creation of a framework for Java Bean mapping

A side effect of an SOA is the passing of domain objects between different systems. Typically, you won't want internal domain objects exposed externally and won't allow for external domain objects to bleed into your system. Creating a mapping framework is useful in a layered architecture where you're creating layers of abstraction by encapsulating changes to particular data objects versus propagating these objects to other layers (i.e., external service data objects, data transfer objects, or internal service data objects). Most programmers will develop some sort of mapping framework and spend countless hours and thousands of lines of code mapping to and from their many transfer objects.

One of the many positive side effects of the refactoring project was the birth of an Open Source project called dozer (http://dozer.sourceforge.net). Dozer was extracted from the refactored code base and made generic enough to handle most real-world mapping scenarios. Dozer supports Java Bean transformation, conversion, simple property mapping, complex type mapping, bidirectional mapping, and implicit/explicit mapping as well as recursive mapping.

Hibernate Through the Cold Winter Nights
Symptom: Scaling and performance issues
Root Cause: Persistence mechanism written with EJB entity beans
Solution: Data access layer with Hibernate and Spring integration

There have been many articles written about the reasons why we shouldn't use entity beans. Some of these reasons are performance issues, an immature query language, and the inability to unit-test and use entity beans as POJOs. Hibernate solves all of these issues and more. Before implementing Hibernate we created a technology-agnostic data access object (DAO) layer. This simply means that if there was an even newer, shinier persistence technology created tomorrow we could replace Hibernate with a minimal amount of refactoring. Some of the immediate benefits of using Hibernate are:

  • The entire DAO layer can be tested without an application server
  • First- and second-tier caching
  • Support for association, inheritance, polymorphism, composition, and the Java collections framework
Spring provides integration with Hibernate for DAO implementation support, resource management, and transaction management. Spring provides a Hibernate interceptor class that manages the Hibernate session throughout a transaction by using Spring's AOP proxying. As a developer you just need to apply that interceptor to any of your Spring wired beans. Spring also lets you define a Hibernate session factory object. An example is presented in Listing 2.

More Stories By Franz Garsombke

Franz Garsombke has been developing and architecting enterprise software solutions in Colorado for the last eleven years and is currently employed at Rally Software. Franz is a huge proponent of open source frameworks and is passionate about developing and delivering simple, quality, pragmatic applications. He is proud to be the co-founder of a Java Bean mapping framework (http://dozer.sourceforge.net) and can be reached at fgarsombke@yahoo.com or on his mountain bike.

Comments (1) View Comments

Share your thoughts on this story.

Add your comment
You must be signed in to add a comment. Sign-in | Register

In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.


Most Recent Comments
JDJ News Desk 10/20/05 07:06:17 PM EDT

Java J2EE Hibernate Extreme Makeover: Architecture Edition. In the past few years there has been a proliferation of frameworks that allow for lighter, faster, and loosely coupled Java projects. These frameworks not only let you decouple your Java project from the application server for unit testing, they also allow for more agile refactoring, testing, and design techniques. This article will focus on telling the story of a large-scale refactoring effort implementing Spring and Hibernate as the underlying infrastructure tools. For those living under an abacus Spring is a J2EE framework built to handle many of the plumbing issues on a typical J2EE application. Hibernate is a popular Open Source Java object/relational persistence framework.