mybatis 学习笔记(四):mybatis 和 spring 的整合

mybatis 学习笔记(四):mybatis 和 spring 的整合

尝试一下整合 mybatis 和 spring。

思路

  • spring通过单例方式管理SqlSessionFactory
  • spring和mybatis整合生成代理对象,使用SqlSessionFactory创建SqlSession。(spring和mybatis整合自动完成)。
  • 持久层的mapper都需要由spring进行管理。

整合环境

在这里我们还是使用 maven 工程来导入 jar 包。

需要用到的 jar 包:

  • spring 核心包和 spring 扩展包如 tx 和 jdbc 等 jar 包
  • mybatis 核心包
  • mybatis 和 spring 整合包
  • java 连接 MySQL 包

实例

在这里我们通过原始 dao 开发和,mapper 代理开发 dao 层两种方式来举例 mybatis 和 spring 整合的操作。

举个栗子:查询数据表中 id 为1的字段。

1

首先通过 maven 导入必要的 jar 包,pom.xml 配置如下:

<?xml version="1.0" encoding="UTF-8"?>
<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/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>cn.itcast</groupId>
    <artifactId>spring-mybatis</artifactId>
    <version>1.0-SNAPSHOT</version>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.6</source>
                    <target>1.6</target>
                </configuration>
            </plugin>
        </plugins>
    </build>

    <dependencies>
        <!-- 测试文件 -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>

        <!-- spring 框架的 jar 包 -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>4.2.4.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>4.2.4.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>4.2.4.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-expression</artifactId>
            <version>4.2.4.RELEASE</version>
        </dependency>

        <!-- spring 拓展包 -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aspects</artifactId>
            <version>4.2.4.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>aopalliance</groupId>
            <artifactId>aopalliance</artifactId>
            <version>1.0</version>
        </dependency>
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.9.1</version>
        </dependency>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-core</artifactId>
            <version>2.11.1</version>
        </dependency>
        <dependency>
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging</artifactId>
            <version>1.2</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>4.2.4.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>4.2.4.RELEASE</version>
        </dependency>

        <!-- mysql 驱动 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.12</version>
        </dependency>
        <!-- mybatis 核心jar包 -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.6</version>
        </dependency>
        <!-- mybatis 附加功能包,如日志功能等 -->
        <dependency>
            <groupId>org.apache.ant</groupId>
            <artifactId>ant</artifactId>
            <version>1.9.6</version>
        </dependency>
        <dependency>
            <groupId>org.apache.ant</groupId>
            <artifactId>ant-launcher</artifactId>
            <version>1.9.6</version>
        </dependency>
        <dependency>
            <groupId>org.ow2.asm</groupId>
            <artifactId>asm</artifactId>
            <version>5.2</version>
        </dependency>
        <dependency>
            <groupId>cglib</groupId>
            <artifactId>cglib</artifactId>
            <version>3.2.5</version>
        </dependency>
        <dependency>
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging</artifactId>
            <version>1.2</version>
        </dependency>
        <dependency>
            <groupId>org.javassist</groupId>
            <artifactId>javassist</artifactId>
            <version>3.22.0-GA</version>
        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-api</artifactId>
            <version>2.3</version>
        </dependency>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-core</artifactId>
            <version>2.3</version>
        </dependency>
        <dependency>
            <groupId>ognl</groupId>
            <artifactId>ognl</artifactId>
            <version>3.1.16</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.7.25</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>1.7.25</version>
            <scope>test</scope>
        </dependency>

        <!-- mybatis 和 spring 整合包 -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>1.3.2</version>
        </dependency>

        <!-- c3po 连接池 -->
        <dependency>
            <groupId>com.mchange</groupId>
            <artifactId>c3p0</artifactId>
            <version>0.9.5.2</version>
        </dependency>
        <dependency>
            <groupId>com.mchange</groupId>
            <artifactId>mchange-commons-java</artifactId>
            <version>0.2.15</version>
        </dependency>

    </dependencies>
</project>

2

然后我们在 resources 下建立 spring 配置文件,mybatis 全局配置文件和映射文件,封装数据库对象,完成后文件目录如图所示:

3

在 application.xml 中配置 sqlSessionFactory 和数据源:

<?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:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
	http://www.springframework.org/schema/beans/spring-beans.xsd
	http://www.springframework.org/schema/context
	http://www.springframework.org/schema/context/spring-context.xsd
	http://www.springframework.org/schema/aop
	http://www.springframework.org/schema/aop/spring-aop.xsd
	http://www.springframework.org/schema/tx
	http://www.springframework.org/schema/tx/spring-tx.xsd">

    <!-- 加载配置文件 -->
    <context:property-placeholder location="classpath:config/db.properties" />

    <!-- 数据源,使用c3p0 -->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
        <!-- 注入属性值 -->
        <property name="driverClass" value="${jdbc.driver}"></property>
        <property name="jdbcUrl" value="${jdbc.url}"></property>
        <property name="user" value="${jdbc.username}"></property>
        <property name="password" value="${jdbc.password}"></property>
    </bean>

    <!-- sqlSessionFactory -->
    <bean id="sqlSessionFactoryBean" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- 加载 mybatis 的配置文件 -->
        <property name="configLocation" value="config/mybatis/SqlMapConfig.xml" />
        <!-- 数据源 -->
        <property name="dataSource" ref="dataSource" />
    </bean>

5

原始的 dao 开发(和 spring整合后)。

  • User.xml
<?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="test">
    <select id="findUserById" parameterType="int" resultType="cn.itcast.ssm.po.User">
        SELECT * FROM USER WHERE id=#{value}
    </select>
</mapper>
  • 在 SqlMapconfig.xml 中加载 User.xml
    <!-- 加载映射文件 -->
    <mappers>
        <mapper resource="config/sqlmap/User.xml"/>
    </mappers>
  • 编写接口 UserDao.java:
package cn.itcast.ssm.dao;

import cn.itcast.ssm.po.User ;

public interface UserDao {
    //根据 id 查询用户信息
    public User findUserById(int id) throws Exception;
}

  • 编写接口实现类 UserDaoImpl.java, 继承 SqlSessionDaoSupport 类:
package cn.itcast.ssm.dao;

import cn.itcast.ssm.po.User;
import org.apache.ibatis.session.SqlSession;
import org.mybatis.spring.support.SqlSessionDaoSupport;

public class UserDaoImpl extends SqlSessionDaoSupport implements UserDao{

    @Override
    public User findUserById(int id) throws Exception {
        //继承SqlSessionDaoSupport,通过this.getSqlSession()得到sqlSessoin
        SqlSession sqlSession = this.getSqlSession();
        User user = sqlSession.selectOne("test.findUserById",id);

        return user;
    }
}
  • 在 applicationContext.xml 中配置 dao:
<!-- 原始 dao 接口 -->
    <bean id="userDao" class="cn.itcast.ssm.dao.UserDaoImpl">
        <property name="sqlSessionFactory" ref="sqlSessionFactoryBean"/>
    </bean>
  • 编写测试类 testFindUserById.java ,进行测试:
package cn.itcast.ssm.dao;

import cn.itcast.ssm.po.User;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.io.InputStream;

public class UserDaoImplTest {

    private ApplicationContext applicationContext;

    //在 setUp这个方法得到 spring 容器
    @Before
    public void setUp() throws Exception{
        applicationContext = new ClassPathXmlApplicationContext("classpath:config/spring/applicationContext.xml");
    }

    @Test
    public void testFindUserById() throws Exception{
        //创建 UserDao 对象
        UserDao userDao = (UserDao) applicationContext.getBean("userDao");

        //调用 UserDao 的方法
        User user = userDao.findUserById(1);

        System.out.println(user);
    }

}
  • 测试结果如下:

6

mapper 代理开发。

同样的,使用mapper 代理开发,只需我们编写接口和配置文件,而不需要关心具体的实现类(mapper 自动生成)。

  • 编写对象接口 UserMapper.java:
package cn.itcast.ssm.mapper;

import cn.itcast.ssm.po.User;

public interface UserMapper {
    //根据 id 查询用户信息
    User findUserById(int id) throws Exception;
}

  • 编写 SQL 语句配置文件 Mapper.xml:
<?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.itcast.ssm.mapper.UserMapper">
    <select id="findUserById" parameterType="int" resultType="user">
        SELECT * FROM USER WHERE ID=#{VALUE }
    </select>
</mapper>
  • 通过 MapperFactoryBean 创建代理对象:
 <!-- mapper配置
    MapperFactoryBean: 根据 mapper 接口生成代理对象
    -->
    <bean id="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
        <!-- mapperInterface指定mapper接口 -->
        <property name="mapperInterface" value="cn.itcast.ssm.mapper.UserMapper"/>
        <property name="sqlSessionFactory" ref="sqlSessionFactoryBean"/>
    </bean>

在此方法中,我们需要针对每个 mapper 进行配置,较为麻烦。

  • 建议通过使用 MapperScannerConfigurer 进行 mapper 扫描:
    <!-- mapper批量扫描,从mapper包中扫描出mapper接口,自动创建代理对象并且在spring容器中注册
    遵循规范:将mapper.java和mapper.xml映射文件名称保持一致,且在一个目录中
    自动扫描出来的mapper的bean的id为mapper类名(首字母小写)
    -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!-- 指定扫描的包名
        如果扫描多个包,每个包中间使用半角逗号分隔
        -->
        <property name="basePackage" value="cn.itcast.ssm.mapper"/>
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactoryBean"/>
    </bean>
  • 编写测试程序,查看执行结果:
package cn.itcast.ssm.mapper;

import cn.itcast.ssm.po.User;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class UserMapperTest {
    private ApplicationContext applicationContext;

    //在 setUp这个方法得到 spring 容器
    @Before
    public void setUp() throws Exception{
        applicationContext = new ClassPathXmlApplicationContext("classpath:config/spring/applicationContext.xml");
    }

    @Test
    public void testFindUserById() throws Exception{
        UserMapper userMapper = (UserMapper) applicationContext.getBean("userMapper");

        //调用 usrMapper 的方法
        User user = userMapper.findUserById(1);

        System.out.println(user);
    }
}

执行结果如下:

posted @ 2018-08-27 13:02  希希里之海  阅读(232)  评论(0编辑  收藏  举报