Spring Book – Chapter 8 – Data Access

RowMapper

An interface used by JdbcTemplate for mapping rows of a ResultSet on a per-row basis. Implementations of this interface perform the actual work of mapping each row to a result object. One very useful thing is that you can collect all the column of one record into java collection and do the operation as required by your application.

Listing 8-37. Usage of RowMapper

ORM Simplification Using Spring

Spring is a framework that plays different roles in many areas of application architecture. One of these areas is persistence. Spring does not provide its own persistence framework. Instead, it provides an abstraction layer over JDBC, and a variety of Object Relational Mapping (ORM) frameworks. This abstraction allows consistent, manageable data-access implementation. All of these comply with Spring’s generic transaction and exception hierarchies. The various ORM frameworks which Spring supports are:

  • Hibernate
  • JPA (Java Persistence API)
  • iBatis SQL Maps
  • Oracle TopLink
  • JDO

In the following sections, we will be discussing integration of Hibernate, iBatis and JPA in some detail.

The various benefits using Spring ORM can be summarized as follows:

  • Easier testing – Spring’s IoC makes it easy to swap the various implementations and config locations of a particular ORM framework. This makes it much easier to isolate and test each piece of persistence-related code in isolation.
  • Common data access exceptions – Spring can wrap exceptions from your O/R mapping tool of choice, converting them from proprietary (potentially checked) exceptions to a common runtime DataAccessException hierarchy. By doing this you can handle all persistence exceptions, which are non-recoverable, without having to write boilerplate catches/throws in your code.
  • General resource management – Spring offers efficient, easy and safe handling of persistence resources. Spring application contexts can handle configuration and other related resources.
  • Integrated transaction management – Spring allows you to wrap your O/R mapping code with either a declarative, AOP style method interceptor, or an explicit ‘template’ wrapper class at the Java code level. You also get the benefit of being able to use and swap various transaction managers, without your ORM related code being affected in any way.

Spring and Hibernate

The beauty of Spring is that it can integrates well with most of the prevailing popular technologies, and in the case of ORM, it integrates well with Hibernate. This section of the chapter examines the means by which Spring can be integrated with Hibernate. I assume that the reader is somewhat familiar with Hibernate and by reading this far familiar with Spring Framework as well to some extend.

ORM is a piece of software/product for the representation and conversion of data between the database and the object-oriented programming language. Hibernate is a powerful technology for persisting data and is a clear winner in the ORM race as of now. However it hasn’t become a standard. It takes much of the database related boiler-plate code from the developers, thereby asking the developers to concentrate on the core business logic of the application and not with the error-prone SQL syntax. It also enables application to access data from any database in a platform-independent manner.

One of the problems with using Hibernate is that the client Application that accesses the database using Hibernate Framework has to depend on the Hibernate APIs. These objects will continue to get scattered across the code throughout the Application. Above all, the application code has to manually maintain and manage these objects. Here comes Spring to the rescue with its IoC container capable of configuring these objects using Spring configurations.

Listings 8-38 through 8-42 show the actual Spring and Hibernate integration in action.  It shows conventional way of mapping the POJO attributes to the database columns. With new Hibernate version you have a provision to avoid the Hibernate mapping files completely by annotating your POJO classes accordingly. The various steps involved are:

1. Database table creation – create the table according to the database that you are using. Since we have taken Customer entity for explaining this integration example, create the customer table with all the relevant columns. For ease of understanding, I will be using only three fields in the Customer entity namely ‘First Name’, ‘Last Name’ and the primary key ‘ID’.

2. POJO (Customer) – we now need to create a class called as Customer which will be used as java equivalent for the Customer table which exists in the database. It is a simple POJO and the class is shown in Listing 8-38  below:

Listing 8-38. Customer POJO class equivalent to Customer table

3. CustomerRepository interface – the interface which the implementation repository classes will implement using appropriate persistence methodologies, in this case Hibernate.

4. Hibernate Mapping File – the file where we actually map the columns of Customer table to the fields in Customer POJO class is achieved by hibernate mapping file. Mapping file is an xml file and its name is customer.hbm.xml. Although this naming convention is not required to be followed but by mere look, will be able to get the relevant information about the file. customer.hbm.xml file contents is shown in the Listing 8-39 below.

Listing 8-39. Customer hibernate mapping file namely customer.hbm.xml

5. Spring Configuration File – this is the file where the various configurations required for Spring are configured. The file is named applicationContext.xml. There are various Spring configurations to be done, which can be sub-divided as below:

a. DataSource configuration – one of the important beans which require mention. Listing 8-40 shows datasource bean configuration which uses MySql database.

Listing 8-40. Spring DataSource bean configuration

b. SessionFactoyBean configuration – The main bean in Hibernate namely SessionFactoryBean is responsible for creating session objects through which transaction and data accessing is achieved. To configure this bean, we have used datasource bean which is already defined, list of mapping files and various Hibernate properties. Listing 8-41. Hibernate SessionFactoryBean bean configuration

c. HibernateTemplate configuration – one of the most important beans which provide a wrapper for low-level data accessing and manipulation using Hibernate is called HibernateTemplate. It contains utility wrapper methods for adding, deleting, updating and finding data in the database.

Listing 8-42. HibernateTemplate bean configuration

d. CustomerRepository/CustomerDao configuration – the client facing class which is made use by the service class to do the nitty-gritties involved in actually doing the low-level activities to fetch data.

Listing 8-43. CustomerRepository bean configuration

6. CustomerRepository/CustomerDao implementation class – here comes the actual implementation of the CustomerRepository implementation class using Hibernate ORM. We will have a new implementation of CustomerRepository interface based on Hibernate and will call it as HibernateCustomerRepository (the one using JDBC, we called as JdbcCustomerRepository in earlier chapters).

Listing 8-41. HibernateCustomerRepository class implementing CustomerRepository implementation

7. TestingClass – dummy testing class used for testing the Spring and Hibernate integration in action. Ideally this will be the actual service class using the repository to call the actual methods which the client will invoke later on.

Listing 8-42. Testing class showing Spring and Hibernate integration in action

I wouldn’t like to spend more time explaining the Spring and Hibernate integration further as there is a wonderful book on this topic titled “Spring Persistence with Hibernate”- (Mybook, November 2010), written by Brian D. Murphy.

Page Visitors: 8721

The following two tabs change content below.
Tomcy John

Tomcy John

Blogger & Author at javacodebook
He is an Enterprise Java Specialist holding a degree in Engineering (B-Tech) with over 10 years of experience in several industries. He's currently working as Principal Architect at Emirates Group IT since 2005. Prior to this he has worked with Oracle Corporation and Ernst & Young. His main specialization is on various web technologies and acts as chief mentor and Architect to facilitate incorporating Spring as Corporate Standard in the organization.
Tomcy John

Latest posts by Tomcy John (see all)

2 thoughts on “Spring Book – Chapter 8 – Data Access

Leave a Reply

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