Spring MyBatis configuration

Here I describe the project configuration to use MyBatis as ORM and benefit of the transactions management provided by Spring.
For that, we have to add the MyBatis-Spring library to the basic MyBatis.

First, the Maven POM is like:

<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis</artifactId>
    <version>3.2.3</version>
</dependency>
<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis-spring</artifactId>
    <version>1.2.1</version>
</dependency>

And now, the Spring configuration file where we define the SqlSessionFactoryBean:

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
                        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">
    
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="mapperLocations" value="classpath:xml/*Mapper.xml" />
    </bean>
</beans>

The SqlSessionFactoryBean needs a datasource, and also the location of the MyBatis xml mappers.

Now, the configuration is done and the mappers will be managed by Spring using with this:

<!-- this is the parent of our Mappers. It defines the sqlSessionFactory which is common to all our mapper beans -->
<bean id="mapper" abstract="true">
	<property name="sqlSessionFactory" ref="sqlSessionFactory" />
</bean>
<!-- Place MyBatis Mappers here -->
<bean id="entityMapper" class="org.mybatis.spring.mapper.MapperFactoryBean" parent="mapper">
	<property name="mapperInterface"
		value="net.classnotfound.data.mapper.EntityMapper" />
</bean>

We can see that the mappers are instantiated by the org.mybatis.spring.mapper.MapperFactoryBean which needs a reference to the SqlSessionFactory object we defined earlier.
To avoid some oversights (and reduce the mount of lines I have to write 🙂 ), I use the “abstract” Spring feature to put the session factory in the abstract mapper, then I can reference it as a parent in all my MapperFactories.

Now the entityMapper we defined is “injectable” in our Spring managed beans and we can use our preferred way of transaction management.

Leave a comment