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
1 2 3 4 5 6 7 8 9 10 11 12 13 |
class TestingClass { public static void main(String args[]) throws Exception { ApplicationContext ac = new ClassPathXmlApplicationContext("aplicationContext.xml", TestingClass.class); DataSource dataSource = (DataSource) ac.getBean("dataSource"); JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource); List names = jdbcTemplate.query("select first_name from customer,new RowMapper() { public Object mapRow(ResultSet resultSet, int i)throws SQLException { return resultSet.getString(1); } }); System.out.println(names); } } |
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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 |
public class Customer { private Long id; private String firstName; private String lastName; public Customer() { } 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 toString(){ return "Id = " + id + ", First Name = " + firstName + ", Last Name = " + lastName; } } |
3. CustomerRepository interface – the interface which the implementation repository classes will implement using appropriate persistence methodologies, in this case Hibernate.
1 2 3 4 5 6 7 |
public interface CustomerRepository { public Customer getCustomer(String customerId); public void saveOrUpdateCustomer(Customer customer); } |
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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
<?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "- //Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-4.0.dtd"> <hibernate-mapping> <class name="com.mybook.sample.Customer" table="Customer"> <id name="id" column="Id"> <generator/> </id> <property name="firstName"> <column name="first_name"/> </property> <property name="lastName"> <column name="last_name"/> </property> </class> </hibernate-mapping> |
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
1 2 3 4 5 6 |
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost/loyalty"/> <property name="username" value="loyalty"/> <property name="password" value="password"/> </bean> |
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
1 2 3 4 5 |
./resources/customer.hbm.xml hibernate.dialect =org.hibernate.dialect.HSQLDialect |
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
1 2 3 4 5 |
<bean id="hibernateTemplate" class="org.springframework.orm.hibernate4.HibernateTemplate"> <property name="sessionFactory"> <ref bean="sessionFactory"/> </property> </bean> |
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
1 2 3 4 5 |
<bean id="customerRepository" class=”com.mybook.sample.repositories.HibernateCustomerRepository”> <property name="hibernateTemplate"> <ref bean="hibernateTemplate"/> </property> </bean> |
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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 |
public class HibernateCustomerRepository implements CustomerRepository{ private HibernateTemplate hibernateTemplate; public void setHibernateTemplate(HibernateTemplate hibernateTemplate){ this.hibernateTemplate = hibernateTemplate; } public HibernateTemplate getHibernateTemplate(){ return hibernateTemplate; } public Customer getCustomer(String customerId){ HibernateCallback callback = new HibernateCallback() { public Object doInHibernate(Session session) throws HibernateException,SQLException { return session.load(Customer.class, customerId); } }; return (Customer)hibernateTemplate.execute(callback); } public void saveOrUpdateCustomer(Customer customer){ HibernateCallback callback = new HibernateCallback() { public Object doInHibernate(Session session) throws HibernateException,SQLException { session.saveOrUpdate(customer); return null; } }; hibernateTemplate.execute(callback); } } |
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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
public class SpringHibernateTestingClass { public static void main(String[] args) { ApplicationContext ac = new ClassPathXmlApplicationContext( "applicationContext.xml", SpringHibernateTestingClass.class); Customer customer = new Customer(); customer.setId(“123”); customer.setFirstName(“john”); customer.setLastName(“smith”); CustomerRepository customerRepository = (CustomerRepository)ac.getBean(“customerRepository”); customerRepository.saveOrUpdateCustomer(customer); Customer createdCustomer = customerRepository.getCustomer(“123”); System.out.println(createdCustomer); } } |
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: 10234

Tomcy John

Latest posts by Tomcy John (see all)
- A Guide to Continuous Improvement for Architects - February 2, 2023
- Cloud-first Architecture Strategy - January 26, 2023
- Architecture Strategy and how to create One - January 24, 2023
Hi my friend! I wish to say that this article is awesome, nice written and come with approximately all important infos. Iˇ¦d like to peer more posts like this .
simple, well written. keep writing..