1,创建maven项目

mvn archetype:generate -DinteractiveMode=false -DgroupId=cn.timd -DartifactId=SpringMybatis -DarchetypeArtifactId=maven-archetype-webapp

2,工程pom

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>cn.timd</groupId>
<artifactId>SpringMybatis</artifactId>
<packaging>jar</packaging>
<version>1.0-SNAPSHOT</version>

<name>SpringMybatis</name>
<url>http://timd.cn/</url>

<properties>
    <spring.version>5.0.2.RELEASE</spring.version>
</properties>

<dependencies>
    <!-- spring -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-core</artifactId>
        <version>${spring.version}</version>
        <exclusions>
            <exclusion>
                <artifactId>commons-logging</artifactId>
                <groupId>commons-logging</groupId>
            </exclusion>
        </exclusions>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-beans</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context-support</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-tx</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-jdbc</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-test</artifactId>
        <version>${spring.version}</version>
    </dependency>

    <!-- db-->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.26</version>
    </dependency>
    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>druid</artifactId>
        <version>1.0.25</version>
    </dependency>

    <!-- SpringMybatisIntegration -->
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.4.5</version>
    </dependency>
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis-spring</artifactId>
        <version>1.3.1</version>
    </dependency>

    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
        <scope>test</scope>
    </dependency>
</dependencies>

<build>
    <finalName>SpringMybatis</finalName>
    <sourceDirectory>src/main/java/</sourceDirectory>
    <resources>
        <resource>
            <directory>src/main/resources/</directory>
            <filtering>true</filtering>
            <includes>
                <include>**/*</include>
            </includes>
        </resource>
    </resources>
</build>

</project>

除了引入了Spring、Mybatis相关的包之外,还引入了mybatis-spring

3,项目结构
spring-mybatis.png

4,DAO

package cn.timd.DAO;

import cn.timd.Entities.User;

public interface UserDao {
    User getUser(int userId);
}

DAO类是一个接口,mybatis-spring会自动实现它。

5,映射文件

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
    "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="cn.timd.DAO.UserDao">
    <sql id="column_names">
        id, name, age
    </sql>
    <select id="getUser" parameterType="int" resultType="cn.timd.Entities.User">
        select
        <include refid="column_names" />
        from tb_user
        where id = #{id}
    </select>
</mapper>

需要注意的是:
1,mapper的namespace必须是DAO接口的全类名
2,<select>、<update>、<delete>标签的id属性必须 和 DAO接口中的 方法同名

6,Spring配置文件

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

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:util="http://www.springframework.org/schema/util"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
">

    <context:component-scan base-package="cn.timd" />

    <util:properties id="db" location="classpath*:db.properties" />

    <bean name="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
        <property name="url" value="#{db.url}" />
        <property name="username" value="#{db.username}" />
        <property name="password" value="#{db.password}" />
        <property name="validationQuery" value="#{db.validation_query}" />
        <property name="initialSize" value="0" />
        <property name="maxActive" value="20" />
        <property name="maxIdle" value="20" />
        <property name="minIdle" value="0" />
        <property name="maxWait" value="60000" />
        <property name="testOnBorrow" value="false" />
        <property name="testOnReturn" value="false" />
        <property name="testWhileIdle" value="true" />
        <property name="timeBetweenEvictionRunsMillis" value="60000" />
        <property name="minEvictableIdleTimeMillis" value="25200000" />
        <property name="removeAbandoned" value="true" />
        <property name="removeAbandonedTimeout" value="1800" />
        <property name="logAbandoned" value="true" />
        <property name="filters" value="mergeStat" />
    </bean>

    <!-- mybatis -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="mapperLocations" value="classpath*:mappers/user/*.xml" />
    </bean>
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="cn.timd.DAO" />
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
    </bean>

</beans>

SqlSessionFactoryBean的属性包括:

等。

MapperScannerConfigurer的属性包括:

等。

6,将DAO注入到Server,并测试

package cn.timd.Services;

import cn.timd.DAO.UserDao;
import cn.timd.Entities.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserService {
    @Autowired
    private UserDao userDao;

    public User getUser(int userId) {
        return userDao.getUser(userId);
    }
}
package cn.timd;

import cn.timd.Services.UserService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Main {
    public static void main(String[] args) {
        ApplicationContext applicationContext =
                new ClassPathXmlApplicationContext("applicationContext.xml");
        UserService userService = (UserService) applicationContext.getBean("userService");
        System.out.println(userService.getUser(101));
    }
}