Integrating MyBatis with Spring Framework

MyBatis-Spring Integration

Before diving into the integration, let's review the core MyBatis components.

Entity Class

package com.example.entity;

public class User {
    private Integer id;
    private String username;
    private String password;

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", password='" + password + '\'' +
                '}';
    }
}

MyBatis Configuration File

<?xml version="1.0" encoding="UTF-8" ?>
<configuration>
    <typeAliases>
        <package name="com.example.entity"/>
    </typeAliases>

    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=false&amp;useUnicode=true&amp;characterEncoding=UTF8"/>
                <property name="username" value="root"/>
                <property name="password" value="123456"/>
            </dataSource>
        </environment>
    </environments>

    <mappers>
        <mapper resource="com/example/mapper/UserMapper.xml"/>
    </mappers>
</configuration>

Mapper Interface

package com.example.mapper;

import com.example.entity.User;
import java.util.List;

public interface UserMapper {
    List<User> findAllUsers();
}

Mapper XML

<?xml version="1.0" encoding="UTF-8" ?>
<mapper namespace="com.example.mapper.UserMapper">
    <select id="findAllUsers" resultType="User">
        SELECT * FROM mybatis.user
    </select>
</mapper>

Standalone Test

public class MyBatisTest {
    @Test
    public void testQuery() throws IOException {
        String configFile = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(configFile);
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession session = factory.openSession(true);

        UserMapper mapper = session.getMapper(UserMapper.class);
        List<User> users = mapper.findAllUsers();

        for (User user : users) {
            System.out.println(user);
        }
    }
}

Integrating MyBatis with Spring

To use MyBatis within a Spring application, you need to configure two main components in the Spring application context: a SqlSessionFactory and at least one mapper implementation.

SqlSessionFactory Configuration

The SqlSessionFactoryBean is used to create the SqlSessionFactory in Spring.

DataSource Setup

Spring can manage the data source, replacing MyBatis's built-in connection pooling options like C3P0, DBCP, or Druid. The simplest approach is using Spring's JDBC data source:

<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
    <property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=false&amp;useUnicode=true&amp;characterEncoding=UTF8"/>
    <property name="username" value="root"/>
    <property name="password" value="123456"/>
</bean>

SqlSessionFactory Bean

<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    <property name="dataSource" ref="dataSource"/>
    <property name="configLocation" value="classpath:mybatis-config.xml"/>
    <property name="mapperLocations" value="classpath:com/example/mapper/UserMapper.xml"/>
</bean>

This configuration replaces the manual SqlSessionFactoryBuilder code from the standalone example. The factory can now be retrieved from the Spring application context.

SqlSessionTemplate

The SqlSessionTemplate is Spring's thread-safe implementation of MyBatis's SqlSession. It must be configured with a SqlSessionFactory through constructor injection:

<bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">
    <constructor-arg index="0" ref="sqlSessionFactory"/>
</bean>

Mapper Implementation

Create a mapper implementation class that uses SqlSessionTemplate:

package com.example.mapper;

import com.example.entity.User;
import org.mybatis.spring.SqlSessionTemplate;
import java.util.List;

public class UserMapperImpl implements UserMapper {
    private SqlSessionTemplate sqlSession;

    public void setSqlSession(SqlSessionTemplate sqlSession) {
        this.sqlSession = sqlSession;
    }

    @Override
    public List<User> findAllUsers() {
        return sqlSession.getMapper(UserMapper.class).findAllUsers();
    }
}

Register this implementation in the Spring context:

<bean id="userMapperImpl" class="com.example.mapper.UserMapperImpl">
    <property name="sqlSession" ref="sqlSessionTemplate"/>
</bean>

Complete Configuration Example

<!-- Data Source -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
    <property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=false&amp;useUnicode=true&amp;characterEncoding=UTF8"/>
    <property name="username" value="root"/>
    <property name="password" value="123456"/>
</bean>

<!-- SqlSessionFactory -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    <property name="dataSource" ref="dataSource"/>
    <property name="configLocation" value="classpath:mybatis-config.xml"/>
    <property name="mapperLocations" value="classpath:com/example/mapper/UserMapper.xml"/>
</bean>

<!-- SqlSessionTemplate -->
<bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">
    <constructor-arg index="0" ref="sqlSessionFactory"/>
</bean>

<!-- Mapper Implementation -->
<bean id="userMapperImpl" class="com.example.mapper.UserMapperImpl">
    <property name="sqlSession" ref="sqlSessionTemplate"/>
</bean>

Integration Test

public class SpringIntegrationTest {
    @Test
    public void test() {
        ApplicationContext context = new ClassPathXmlApplicationContext("spring-mapper.xml");
        UserMapperImpl mapperImpl = context.getBean("userMapperImpl", UserMapperImpl.class);
        
        for (User user : mapperImpl.findAllUsers()) {
            System.out.println(user);
        }
    }
}

SqlSessionDaoSupport

SqlSessionDaoSupport is an abstract support clas that provides SqlSession acccess through the getSqlSession() method, returning a SqlSessionTemplate instance. This class can be extended by mapper implementations to simplify the integration pattern.

Tags: MyBatis Spring java ORM database

Posted on Thu, 07 May 2026 15:42:21 +0000 by binarymonkey