mybatis学习之与Spring整合

来源:互联网 发布:封装继承多态java 编辑:程序博客网 时间:2024/06/05 10:02

整合思路

需要spring通过单例模式管理SQLSessionFactory
Spring和mybatis整合生成代理对象,使用SQLSessionFactory创建SQLSession(Spring和mybatis整合自动完成)
 
持久层的mapper,dao都需要由spring管理

整合环境

创建一个新的java工程(接近实际开发的工程结构)
jar包:
mybatis的jar包(3.4.4)
spring的jar包(3.2.0 )
mybatis 和 spring的整合包(1.2.2):早期ibatis和spring整合室友spring官方提供,如今mybatis和spring整合由mybatis提供

所有jar包:

建立工程结构:

配置SqlSessionFactory


在applicationContext里配置SQLSessionFactory

SQLSessionFactory在mybatis和spring的整合包下

applicationContext的首部:
<beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"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-3.2.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd "></beans>


注意:在定义sqlSessionFactory时指定数据源dataSource和mybatis的配置文件。


配置Spring的applicationContext第一步:加载数据库连接配置文件(没有请忽略)

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

配置Spring的applicationContext第二步:加载数据源

    <!-- 数据源,使用DBCP -->    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">        <property name="driverClassName" value="${jdbc.driver}" />        <property name="url" value="${jdbc.url}" />        <property name="username" value="${jdbc.username}" />        <property name="password" value="${jdbc.password}" />        <property name="maxActive" value="10" />        <property name="maxIdle" value="5" />    </bean>
配置Spring的applicationContext第三步:配置SQLSessionFactory

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


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

1、创建mapper.xml

在classpath目录下创建包:sqlmap

在sqlmap目录下创建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"><!--namespace命名空间,作用就是对于sql进行分类管理,理解为sql隔离注意:使用mapper代理的方法开发,namespace就有特殊的重要作用 --><mapper namespace="test">    <!-- 在映射文件中配置很多sql语句 -->    <!--    需求:通过id查询用户数据    -->    <!--    通过select来执行数据库的查询操作    ID:标识映射文件中的sql,成为statementid    将sql语句封装到mappedStatement对象中    parameterType: 指定输入参数的类型,这里指定为int型    #{}表示一个占位符    #{id},其中的id表示接受输入的参数,参数名称为id    resultType : 指定sql输出结果所映射的java对象类型,这里select指定resultType表示单条记录所映射成的java对象    -->    <select id="findUserById" parameterType="int" resultType="alex.ssm.po.User">        SELECT * FROM USER WHERE id = #{id}    </select></mapper>

在SqlMapConfig.xml中加载User.xml

        <!-- 通过resource方法来一次加载一个映射文件 -->        <mapper resource="sqlmap/User.xml" />

2、DAO(实现类继承SqlSessionDaoSupport)

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


让UserDaoImpl实现类继承SqlSessionDaoSupport类

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

3、配置dao

在applicationContext.xml中配置DAO

DAO的接口实现类中,需要注入SQLSessionFactory,在此处我们通过spring进行注入


这里使用spring的声明配置方式,配置dao的bean:

    <!-- 原始DAO接口 -->    <bean id="userDao" class="alex.ssm.dao.UserDaoImpl">        <property name="sqlSessionFactory" ref="SqlSessionFactory" />    </bean>

4、测试程序

public class userTest extends TestCase {    //在setUp方法中,要得到spring的容器    private ApplicationContext applicationContext;    @Before    public void setUp() throws Exception{        applicationContext = new ClassPathXmlApplicationContext("classpath:spring/applicationContext.xml");    }    @Test    public void testFindUserById() throws Exception{        //从spring配置文件中拿到userDao        UserDao userDao = (UserDao)applicationContext.getBean("userDao");        //调用UserDao的方法        User user = userDao.findUserById(29);        //输出        System.out.println(user);    }}

5、输出结果



Mapper代理开发(与spring整合)

1、mapper.xml和mapper.java

<?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"><!--namespace命名空间,作用就是对于sql进行分类管理,理解为sql隔离注意:使用mapper代理的方法开发,namespace就有特殊的重要作用,namespace 等于 mapper 接口的地址 --><mapper namespace="alex.ssm.mapper.UserMapper">    <!-- 在映射文件中配置很多sql语句 -->    <!--    需求:通过id查询用户数据    -->    <!--    通过select来执行数据库的查询操作    ID:标识映射文件中的sql,成为statementid    将sql语句封装到mappedStatement对象中    parameterType: 指定输入参数的类型,这里指定为int型    #{}表示一个占位符    #{id},其中的id表示接受输入的参数,参数名称为id    resultType : 指定sql输出结果所映射的java对象类型,这里select指定resultType表示单条记录所映射成的java对象    -->    <select id="findUserById" parameterType="int" resultType="user">        SELECT * FROM USER WHERE id = #{id}    </select></mapper>


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



2、spring通过mapperFactoryBean创建代理对象

在applicationContext中加入
    <!--    mapper的配置    MapperFactoryBean:根据mapper接口生成代理对象    -->    <bean id="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">        <!-- mapperInterface 指定mapper接口类 -->        <property name="mapperInterface" value="alex.ssm.mapper.UserMapper"/>        <property name="sqlSessionFactory" ref="SqlSessionFactory" />    </bean>


此种方法问题:
需要针对每一个mapper进行配置, 麻烦。

3、或者通过MapperScannerConfigurer进行mapper扫描(推荐)

在applicationContext.xml文件中,将之前的mapper加载配置删除,新加入:
    <!--    mapper 的批量扫描 , 从mapper的包中扫描出mapper的接口,自动创建代理对象,并在spring 的容器中注入    需要遵循一些规范:需要将mapper接口类名和mapper.xml的文件名称保持一致,且在一个目录    -->    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">        <!-- 指定扫描的包名 -->        <property name="basePackage" value="alex.ssm.mapper" />        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />    </bean>
注意:在此处,我的spring版本为3.2.0 而 jdk版本却使用了1.8,所以导致出现了IllegalArgumentException 问题,在将jdk版本降成1.6后,该问题成功解决。

4、测试代码

    @Test    public void testFindUserByIdMapper() throws Exception{        //从spring配置文件中拿到userMapper        UserMapper userMapper = (UserMapper)applicationContext.getBean("userMapper");        //调用UserDao的方法        User user = userMapper.findUserById(29);        //输出        System.out.println(user);    }
注意,在此处,若设置了Spring的mapper扫描,那么在mybatis 的配置文件中的package扫描即可去掉,即:

        <!--        批量加载mapper        指定mapper接口类的包名        mybatis自动扫描该包目录下所有的mapper接口类        需要遵循一些规范:需要将mapper接口类名和mapper.xml的文件名称保持一致,且在一个目录        使用的前提:使用mapper代理的方法开发DAO        和spring整合后,在spring使用了MapperScannerConfigurer后,可以去掉该配置         -->        <!--<package name="alex.ssm.mapper" />-->




5、执行结果


原创粉丝点击