Using Spring 3 with Mybatis 3 Tutorial – part 1

Posted: May 14, 2012 in Techilla
Tags: , , ,

We are going to use Spring 3x and Mybatis 3x in conjunction here.

Pre-requisite :
Download the Mybatis-Spring bundle : mybatis-spring-1.1.1-bundle and use the libs assorted.
Spring version : 3.1.1
Mybatis version : 3.1.0
Please note the version 1.1.1 for mybatis-spring bundle. There were some issues with 1.1.0 bundle for loading of properties using Spring’s PropertyPlaceHolderConfigurer, but more on that later.


Mybatis is a persistence framework. Mybatis is not an ORM framework and doesn’t map Java objects to database rows. However, it maps methods to SQL statements.

Mybatis vs. Hibernate

I have used both Mybatis and Hibernate in my applications, and both have their pros and cons. However, of late, I have moved more and more towards Mybatis.

IMO, if the object graph is complex, then it is better to use Mybatis and not Hibernate. Hibernate has its own version of lazy loading, but the more associations an object has or the heavier an object is, the more it becomes a performance hit.

In one of our applications which used Hibernate, we finally had to rewrite several queries in order to perform thin loading, or loading only those attributes which are required.

For further details regarding Mybatis, please visit
For Spring-Mybatis, :here

Spring vs Struts for MVC

As regards Spring vs Struts for MVC, again to each his own. Struts 2x is pretty good when it comes to writing less code to do more and I had recently developed an application using Struts 2x. However, most of the transaction management there was programmatic, which needless to say is ugly and error prone. I had to spend lots of time testing out my code.

Now, this last statement is not strictly a Spring MVC advantage or a Struts flaw, because its just an MVC framework and nothing more. However, when we talk about Spring, we get to use the IOC container as well along with its declarative transaction management. Plus, the community support is really good, which invariably helps if you hit a roadblock. One more thing, which I really like about Spring is its view-agnostic (Yes I picked up this word somewhere on the net) It means that it really allows you to custom build any view implementation you like and not just stick to JSPs.(Though Struts 2x has some similar implementations using FreeMarker)

We would be using Eclipse as an IDE to do our development and this is an image of all jars which will be required eventually. Some of them like the commons*.jar and mybatis-ehcache*.jar will have to be downloaded separately.

spring mybatis libs/ jars

Since, by now we have a working Spring MVC application here, we will piggyback on it and add the required configurations. We will revisit our application’s web.xml. (This is just the relevant part, for the entire xml, please refer here.)


Right, so from here we can see that the ContextLoaderListener will check on

  1. database-config.xml which will contain the database configuration.
  2. mapper-config.xml which will point to the individual Mybatis interfaces.
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
 <property name="driverClassName" value="${driver}" />
 <property name="url" value="${url}" />
 <property name="username" value="${username}" />
 <property name="password" value="${password}" />
 <property name="defaultAutoCommit" value="false" />
<bean id="txManager"
 <property name="dataSource" ref="dataSource" />
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
 <property name="dataSource" ref="dataSource" />
 <property name="mapperLocations" value="classpath:com/mybatis/mappers/*.xml" />
 <property name="configLocation" value="WEB-INF/mybatis-config/mybatis-config.xml" />

We see 3 beans here :dataSource, txManager and sqlSessionFactory . For dataSource, we will be using dbcp’s BasicDataSource. We would come to the txmanager later.

Now, if you are observant, you would see that the credentials of the datasource are encoded. This is an industry standard, where sensitive information is stored on a keystore or an external property file. Then, the access for this file is controlled by the system administrators on the server. We would see later how, Spring help to retrieve these property values.

For now, let’s concentrate only on the sqlSessionFactory and its attributes.

It has 3 attributes :

  1. refers to the dataSource,
  2. mapperLocations which is where we would store our mybatis xml files. Ant style configuration for mapperLocation: if we put it as value=“classpath*:com/mybatis/mappers/*.xml” /> then it will also look into the subpackages recursively
  3. configLocation where we would store a custom mybatis configuration file to override some important settings.


<bean id="baseMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
 <property name="mapperInterface" value="com.mybatis.dao.BaseMapperInterface" />
 <property name="sqlSessionFactory" ref="sqlSessionFactory" />
<bean id="employeeMapper" parent="baseMapper">
 <property name="mapperInterface" value="com.mybatis.dao.EmployeeMapperInterface" />

2 important concepts explained here:

  1. We have a BaseMapperInterface which contains a reference to the sqlSessionFactory and this class is simply extended by the rest of the mapper interfaces so that individual interfaces do not have to link in the sqlSessionFactory.
  2. Presence of a MapperFactoryBean which we will revisit later.


This is a bare-bones configuration file which we will augment as we learn more about Mybatis.

<?xml version="1.0" encoding="UTF-8" ?>
 <!DOCTYPE configuration
 PUBLIC "-// Config 3.0//EN"
 <setting name="cacheEnabled" value="true" />
 <setting name="lazyLoadingEnabled" value="true" />
 <setting name="multipleResultSetsEnabled" value="true" />
 <setting name="useColumnLabel" value="true" />
 <setting name="useGeneratedKeys" value="false" />
 <setting name="defaultExecutorType" value="SIMPLE" />
 <setting name="defaultStatementTimeout" value="100" />
 <setting name="safeRowBoundsEnabled" value="false" />
 <setting name="mapUnderscoreToCamelCase" value="false" />
 <setting name="localCacheScope" value="SESSION" />
 <setting name="jdbcTypeForNull" value="OTHER" />
 <setting name="lazyLoadTriggerMethods" value="equals,clone,hashCode,toString" />

So, we have done our configurations. One more small thing of using Spring to decipher the properties for us. We can put this in the app-config.xml which is also listened to by the ContextLoaderListener(check the web.xml earlier on this page)

<bean class=<em>"org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"</em>>
<property name="location">

Interesting Note: we can use our custom PropertyPlaceHolderConfigurer by extending the above mentioned class.We only need to override the following method :

public String convertPropertyValue(final String originalValue) {
//whatever decoding/decrypting logic u want to put.
//U can first encrypt and then encode the property in the property file.

Right, so our configurational changes have been completed.

Now a typical approach is having the service layer get access to the Mapper interfaces.

So, the interaction would be like Controller(Web layer) accesses the Service Façade which accesses the Mybatis DAO layer/interfaces.

Our sample application would have a login screen for a manager. When the manager successfully logs in, he or she would be able to view his/her employees. On clicking any of the employee’s hyperlink, the manager would get access to the employee’s details which can then be modified.

In step 2, we will be creating our controllers.

This tutorial has been linked in Mybatis wiki :

  1. […] anirbanchowdhury Just another site Skip to content HomeAbout Me ← Using Spring 3 with Mybatis 3 Tutorial – part 1 […]

  2. […] anirbanchowdhury Just another site Skip to content HomeAbout Me ← Using Spring 3 with Mybatis 3 Tutorial – part 1 […]

  3. Bos JavaGini says:

    Thanks for nice post. Do you have a project / pom created for this sample? It will make life easy.

  4. Rahul Sinha says:

    Thank you for such a wonderful and elaborate tutorial.

  5. volodiaL says:

    Thanks for this important free tutorial.

    I can’t figure out what mapper-config.xml is about. And why does EmployeeMapperImpl extends SqlSessionDaoSupport ?
    Can you provide full source code?

  6. Prashanth Y R says:

    Simple, Clear and Perfect!
    Thanks Anirban.

  7. jack.liu says:

    Thanks for your sharing very much!Your article is useful!

    — A programmer from China.

  8. opendataexpert says:

    I am new to it. Where should I put configuration files?

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s