文章目录

  • Spring整合MyBatis
  • 整合方式一:SqlSessionTemplate
  • 整合方式二:SqlSessionDaoSupport
  • 整合方式三:MapperFactoryBean
  • 整合方式四:MapperScannerConfigurer


Spring整合MyBatis

整合方式一:SqlSessionTemplate

项目依赖:

在之前项目的框架下,新建模块spring-06,导入需要的jar。

父项目

<dependencies>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>5.2.9.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
        <scope>test</scope>
    </dependency>
</dependencies>

spring-06模块

<dependencies>
    <!--AOP-->
    <dependency>
        <groupId>org.aspectj</groupId>
        <artifactId>aspectjweaver</artifactId>
        <version>1.9.6</version>
    </dependency>
    <dependency>
        <groupId>aopalliance</groupId>
        <artifactId>aopalliance</artifactId>
        <version>1.0</version>
    </dependency>
    <!--Spring-->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-jdbc</artifactId>
        <version>5.2.9.RELEASE</version>
    </dependency>
    <!--MyBatis-->
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.4.6</version>
    </dependency>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.47</version>
    </dependency>
    <!--MyBatis整合Spring-->
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis-spring</artifactId>
        <version>2.0.5</version>
    </dependency>
    <!--DBCP-->
    <dependency>
        <groupId>commons-dbcp</groupId>
        <artifactId>commons-dbcp</artifactId>
        <version>1.4</version>
    </dependency>
    <dependency>
        <groupId>commons-pool</groupId>
        <artifactId>commons-pool</artifactId>
        <version>1.6</version>
    </dependency>
    <!--log4j-->
    <dependency>
        <groupId>log4j</groupId>
        <artifactId>log4j</artifactId>
        <version>1.2.17</version>
    </dependency>
</dependencies>

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-5fFPmrxD-1602233858755)(Spring.assets/1602153473161.png)]

使用MyBatis-Genator工具生成user表的实体类、UsersMapper接口和映射文件。

项目目录结构:

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-cUNu1fZD-1602233858758)(Spring.assets/1602221986239.png)]

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:p="http://www.springframework.org/schema/p"
       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/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
                           http://www.springframework.org/schema/context
                           http://www.springframework.org/schema/context/spring-context.xsd">
    <!--注解 + 扫描-->
    <context:component-scan base-package="org.westos"/>

    <!--引入外部属性文件-->
    <context:property-placeholder location="dbcp.properties"/>

    <!--DBCP数据源-->
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
        <property name="driverClassName" value="${jdbc.driverClassName}"/>
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
    </bean>

    <!--创建SqlSessionFactory-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!--传入数据源-->
        <property name="dataSource" ref="dataSource"/>
        <!--引用MyBatis配置文件中的配置-->
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
        <!--配置MyBatis映射文件的位置-->
        <property name="mapperLocations">
            <list>
                <value>classpath:org/westos/mapper/**/*.xml</value>
            </list>
        </property>
    </bean>

    <!--方式一:Spring提供了SqlSessionTemplate,方便我们操作-->
    <bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">
        <!--通过有参构造函数注入SqlSessionFactory-->
        <constructor-arg name="sqlSessionFactory" ref="sqlSessionFactory"/>
    </bean>
</beans>

MyBatis配置文件

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <typeAliases>
        <package name="org.westos.entity"/>
    </typeAliases>
</configuration>

MyBatis映射文件

<?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="org.westos.mapper.UsersMapper">
    <select id="selectAll" resultType="Users">
        select * from users;
    </select>
</mapper>

Mapper层

@Repository
public class UsersMapperImpl implements UsersMapper {
    @Autowired
    private SqlSessionTemplate sqlSessionTemplate;

    /**
     * 查询所有用户的DAO层实现
     * @return
     */
    @Override
    public List<Users> selectAll() {
        return sqlSessionTemplate.selectList("org.westos.mapper.UsersMapper.selectAll");
    }
}

通过注入SqlSessionTemplate来实现查询,类似于SqlSesion的查询方法。

Service层

@Service
public class UsersServiceImpl implements UsersService {
    @Autowired
    private UsersMapper usersMapper;
    /**
     * 业务层的查询所有
     * @return
     */
    @Override
    public List<Users> selectAll() {
        return usersMapper.selectAll();
    }
}

测试方法

@Test
public void test() {
    //测试整合方式一:SqlSessionTemplate
    ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
    UsersService usersService = (UsersService) context.getBean("usersServiceImpl");
    List<Users> users = usersService.selectAll();
    System.out.println(users.size());
    System.out.println(users.get(5));
}
9
Users{id=22, name='qiaximao', address='上海市华夏路100号', phone='13774210000', mail='qiximao@163.com', userstateid=1, isonline=0, loginid='恰嬉猫', loginpwd='070115', userroleid=1, gender=0}

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-bjcj4BsY-1602233858760)(Spring.assets/1602222283207.png)]

整合方式二:SqlSessionDaoSupport

利用和上一个模块一样的pom.xml文件,新建spring-07模块。

第一种方式的缺陷在于,每一个XxxMapper的实现类都需要注入一个SqlSessioinTemplate,显得繁琐。

public class UsersMapperImpl extends SqlSessionDaoSupport implements UsersMapper {
    /**
     * 查询所有用户,利用SqlSessionDaoSupport类中的getSession()方法
     * SqlSession,作用域应该为方法级别
     * @return
     */
    @Override
    public List<Users> selectAll() {
        return this.getSqlSession().selectList("org.westos.mapper.UsersMapper.selectAll");
    }
}
<?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:p="http://www.springframework.org/schema/p"
       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/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
                           http://www.springframework.org/schema/context
                           http://www.springframework.org/schema/context/spring-context.xsd">
    <!--注解 + 扫描-->
    <context:component-scan base-package="org.westos"/>

    <!--引入外部属性文件-->
    <context:property-placeholder location="dbcp.properties"/>

    <!--DBCP数据源-->
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
        <property name="driverClassName" value="${jdbc.driverClassName}"/>
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
    </bean>

    <!--创建SqlSessionFactory-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!--传入数据源-->
        <property name="dataSource" ref="dataSource"/>
        <!--引用MyBatis配置文件中的配置-->
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
        <!--配置MyBatis映射文件的位置-->
        <property name="mapperLocations">
            <list>
                <value>classpath:org/westos/mapper/**/*.xml</value>
            </list>
        </property>
    </bean>

    <!--方式二:利用SqlSessionDaoSupport-->
    <!--创建UsersMapperImpl对象,因为它继承了SqlSessionDaoSupport,所以可以注入SqlSessionFactory-->
    <bean id="usersMapperImpl" class="org.westos.mapper.impl.UsersMapperImpl">
        <property name="sqlSessionFactory" ref="sqlSessionFactory"/>
    </bean>
</beans>

测试成功。

整合方式三:MapperFactoryBean

前面两种是存在Mapper接口实现类的方式,还是较为繁琐。

public class UsersServiceImpl implements UsersService {
    private UsersMapper usersMapper;

    public void setUsersMapper(UsersMapper usersMapper) {
        this.usersMapper = usersMapper;
    }

    /**
     * 业务层的查询所有
     * @return
     */
    @Override
    public List<Users> selectAll() {
        return usersMapper.selectAll();
    }
}
<?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:p="http://www.springframework.org/schema/p"
       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/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
                           http://www.springframework.org/schema/context
                           http://www.springframework.org/schema/context/spring-context.xsd">
    <!--注解 + 扫描-->
    <context:component-scan base-package="org.westos"/>

    <!--引入外部属性文件-->
    <context:property-placeholder location="dbcp.properties"/>

    <!--DBCP数据源-->
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
        <property name="driverClassName" value="${jdbc.driverClassName}"/>
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
    </bean>

    <!--创建SqlSessionFactory-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!--传入数据源-->
        <property name="dataSource" ref="dataSource"/>
        <!--引用MyBatis配置文件中的配置-->
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
    </bean>

    <!--方式三:利用MapperFactoryBean-->
    <bean id="usersMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
        <property name="sqlSessionFactory" ref="sqlSessionFactory"/>
        <property name="mapperInterface" value="org.westos.mapper.UsersMapper"/>
    </bean>

    <!--将MapperFactoryBean注入到UsersServiceImpl的usersMapper  -->
    <bean id="usersService" class="org.westos.service.impl.UsersServiceImpl">
        <property name="usersMapper" ref="usersMapper"/>
    </bean>
</beans>

测试成功。

整合方式四:MapperScannerConfigurer

推荐使用,最终版。

@MapperScan
public interface UsersMapper {
    /**
     * 查询所有用户
     * @return
     */
    List<Users> selectAll();
}
@Service
public class UsersServiceImpl implements UsersService {
    @Autowired
    private UsersMapper usersMapper;

    /**
     * 业务层的查询所有
     * @return
     */
    @Override
    public List<Users> selectAll() {
        return usersMapper.selectAll();
    }
}
<?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:p="http://www.springframework.org/schema/p"
       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/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
                           http://www.springframework.org/schema/context
                           http://www.springframework.org/schema/context/spring-context.xsd">
    <!--注解 + 扫描-->
    <context:component-scan base-package="org.westos"/>

    <!--引入外部属性文件-->
    <context:property-placeholder location="dbcp.properties"/>

    <!--DBCP数据源-->
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
        <property name="driverClassName" value="${jdbc.driverClassName}"/>
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
    </bean>

    <!--创建SqlSessionFactory-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!--传入数据源-->
        <property name="dataSource" ref="dataSource"/>
        <!--引用MyBatis配置文件中的配置-->
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
    </bean>

    <!--方式四:MapperScannerConfigurer-->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="org.westos.mapper"/>
    </bean>
</beans>

测试成功。