MyBatis Spring example 2018-08-19 05:47

In this page I will show you how to integrate MyBatis and Spring. I use maven to build the project. The structure of the project is like following.

│  ├─java
│  │  └─com
│  │      └─henryxi
│  │          ├─controller
│  │          │
│  │          │
│  │          ├─entity
│  │          │
│  │          │
│  │          └─mapper
│  │        
│  │
│  ├─resources
│  │      application.xml
│  │      mybatis.xml
│  │
│  └─webapp
│      └─WEB-INF
│              web.xml

The content of web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns=""


The content of application.xml

<beans xmlns=""
    <context:component-scan base-package="com.henryxi"/>

    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="configLocation" value="classpath:mybatis.xml"/>

    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.henryxi.mapper"/>

    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
        <property name="driverClassName" value="com.mysql.jdbc.Driver">
        <property name="url" value="jdbc:mysql://"/>
        <property name="username" value="root"/>
        <property name="password" value="123456"/>


The content of mybatis.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
        PUBLIC "-// Config 3.1//EN"
        <property name="dialect" value="mysql"/>

For the java code they are all here

public class UserController {

    private UserMapper userMapper;

    public User get(@RequestParam("id") int id) {
        User user = userMapper.getUser(id);
        return user;

    public String save(@RequestParam("id") int id, @RequestParam("name") String name) {, name);
        return "succ";

public class User implements Serializable{
    private int id;
    private String name;

    public int getId() {
        return id;

    public void setId(int id) { = id;

    public String getName() {
        return name;

    public void setName(String name) { = name;

    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +

public interface UserMapper {
    @Select("SELECT * FROM users WHERE id = #{userId}")
    User getUser(@Param("userId") int userId);

    @Insert("INSERT INTO users (id, name) VALUES (#{userId},#{userName}) ")
    void save(@Param("userId") int userId, @Param("userName") String userName);

Before you run this example you need to create database test_db or other name you like. Then create the table users. The sql of creating table is here.

CREATE TABLE `users` (
  `id` int(10) unsigned NOT NULL,
  `name` varchar(50) NOT NULL,
  PRIMARY KEY (`id`)

After all steps are done. You can access 'localhost:8080/save?id=6&name=henry' to save user and access 'localhost:8080/get?id=6' to get the info of the user.