• Mybatis3详解(十五)——Mybatis整合Spring框架


    1、前言

           前面的十几篇文章都单独的总结了Mybatis在开发中的相关技术,但在实际开发中一般都是和Spring进行整合开发的,而Spring框架相信大家已经非常熟悉了,通过Spring的IOC/DI,能帮助我们完成对象的创建,对象之间的依赖,并且管理对象的声明周期,而Spring的AOP也能帮助我们管理对象的事务。所以下面我们来实现Mybatis和Spring的整合,并在整合后进行简单的测试。

    2、创建maven项目

           ①、项目整体目录

    image

           ②、导入依赖(双击快速复制)

            <!-- 添加Spring支持 -->
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-core</artifactId>
                <version>5.2.6.RELEASE</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-beans</artifactId>
                <version>5.2.6.RELEASE</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-tx</artifactId>
                <version>5.2.6.RELEASE</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-context</artifactId>
                <version>5.2.6.RELEASE</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-aop</artifactId>
                <version>5.2.6.RELEASE</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-aspects</artifactId>
                <version>5.2.6.RELEASE</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-jdbc</artifactId>
                <version>5.2.6.RELEASE</version>
            </dependency>
            <!-- Mybatis -->
            <dependency>
                <groupId>org.mybatis</groupId>
                <artifactId>mybatis</artifactId>
                <version>3.5.6</version>
            </dependency>
            <!-- Mybatis-Spring -->
            <dependency>
                <groupId>org.mybatis</groupId>
                <artifactId>mybatis-spring</artifactId>
                <version>2.0.3</version>
            </dependency>
            <!-- Mysql驱动 -->
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <version>8.0.21</version>
            </dependency>
            <!-- Druid数据库连接池 -->
            <dependency>
                <groupId>com.alibaba</groupId>
                <artifactId>druid</artifactId>
                <version>1.2.1</version>
            </dependency>
            <!-- 日志处理 -->
            <dependency>
                <groupId>log4j</groupId>
                <artifactId>log4j</artifactId>
                <version>1.2.17</version>
            </dependency>
            <!-- 单元测试 -->
            <dependency>
                <groupId>junit</groupId>
                <artifactId>junit</artifactId>
                <version>4.12</version>
            </dependency>

    3、编写实体类、Mapper接口以及Mapper.xml文件

           ①、User实体类

    /**
     * 用户实体类
     */
    public class User implements Serializable {
        private int userId;
        private String userName;
        private int userAge;
        private Date userBirthday;
        private int userSex;
        private String userAddress;
    
        //getter、setter、toString方法省略......
    }

           ②、UserMapper接口

    /**
     * UserMapper接口
     */
    public interface UserMapper {
        //查询所有用户信息
        List<User> selectAllUser();
    }

           ③、UserMapper.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="com.thr.mapper.UserMapper">
    
        <resultMap id="userMap" type="com.thr.pojo.User">
            <id property="userId" column="id"/>
            <result property="userName" column="username"/>
            <result property="userAge" column="age"/>
            <result property="userBirthday" column="birthday"/>
            <result property="userSex" column="sex"/>
            <result property="userAddress" column="address"/>
        </resultMap>
    
        <!-- 查询所有用户 -->
        <select id="selectAllUser" resultMap="userMap">
            select * from t_user
        </select>
    </mapper>
    

    5、编写数据库连接文件和日志文件

           ①、db.properties

    #数据库连接配置
    database.driver=com.mysql.cj.jdbc.Driver
    database.url=jdbc:mysql://localhost:3306/mybatis?serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=utf-8
    database.username=root
    database.password=root

           ②、log4j.properties

    log4j.rootLogger=DEBUG, Console
    #Console
    log4j.appender.Console=org.apache.log4j.ConsoleAppender
    log4j.appender.Console.layout=org.apache.log4j.PatternLayout
    log4j.appender.Console.layout.ConversionPattern=%d [%t] %-5p [%c] - %m%n
    log4j.logger.java.sql.ResultSet=INFO
    log4j.logger.org.apache=INFO
    log4j.logger.java.sql.Connection=DEBUG
    log4j.logger.java.sql.Statement=DEBUG
    log4j.logger.java.sql.PreparedStatement=DEBUG

    6、编写Mybatis全局配置文件mybatis-config.xml

           这里几乎没什么可配置的,都整合到Spring的配置文件中去了。

    <?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>
        <settings>
            <!--开启日志-->
            <setting name="logImpl" value="STDOUT_LOGGING" />
        </settings>
    </configuration>

    7、编写Spring全局配置文件applicationContext.xml

           在与Spring整合之前,我们都是在Mybatis的全局配置文件中管理数据源,并且sqlSessionFactory也是我们自己通过代码来完成注入的,但是现在与Spring整合了,这些操作都要交给Spring来管理了,所以下面我们来看一下applicationContext.xml 文件中的配置:

    <?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"
           xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans.xsd
           http://www.springframework.org/schema/context
           https://www.springframework.org/schema/context/spring-context.xsd">
    
        <!-- 加载classpath下的db.properties文件 -->
        <context:property-placeholder location="classpath:db.properties"/>
    
        <!-- 配置数据源 -->
        <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
            <property name="driverClassName" value="${database.driver}" />
            <property name="url" value="${database.url}" />
            <property name="username" value="${database.username}" />
            <property name="password" value="${database.password}" />
        </bean>
    
        <!-- 配置sqlSessionFactory,SqlSessionFactoryBean是用来产生sqlSessionFactory的 -->
        <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
            <!-- 加载上面配置好数据源 -->
            <property name="dataSource" ref="dataSource" />
            <!-- 加载mybatis的映射配置文件;XxxMapper.xml -->
            <property name="mapperLocations" value="classpath:com/thr/mapper/*.xml" />
            <!-- 加载mybatis的全局配置文件;mybatis-config.xml-->
            <property name="configLocation" value="classpath:mybatis-config.xml"/>
            <!-- 配置别名,使用包扫描,扫描com.thr.pojo包下的所有实体 -->
            <property name="typeAliasesPackage" value="com.thr.pojo"/>
        </bean>
    
        <!-- 创建UserMapper接口的代理对象,这里是创建单个代理对象,不推荐这种方式,如果多个类就麻烦了
        这里的org.mybatis.spring.mapper.MapperFactoryBean<T>类就是用来创建 Mapper代理对象的类 -->
        <!--
        <bean id="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
            <property name="mapperInterface" value="com.thr.mapper.UserMapper"/>
            <property name="sqlSessionFactory" ref="sqlSessionFactory"/>
        </bean>
        -->
    
        <!-- 加载所在包名下的Mapper接口,并且为其创建代理对象,推荐 -->
        <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
            <property name="basePackage" value="com.thr.mapper" />
            <!-- 可选,如果不写,Spring启动时候。容器中自动会按照类型去把SqlSessionFactory对象注入进来 -->
            <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
        </bean>
    </beans>
    

    8、编写测试代码与运行结果

           ①、测试代码

    package com.thr.test;
    
    import com.thr.mapper.UserMapper;
    import com.thr.pojo.User;
    import org.junit.Before;
    import org.junit.Test;
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.support.ClassPathXmlApplicationContext;
    
    import java.util.List;
    
    public class UserMapperTest {
        //创建ApplicationContext容器
        private ApplicationContext applicationContext = null;
    
        @Before
        public void getApplicationContext() throws Exception {
            //获取Spring容器
            applicationContext = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
        }
        //查询所有用户
        @Test
        public void testSelectAllUser(){
            //获取UserMapper对象
            UserMapper userMapper = applicationContext.getBean("userMapper", UserMapper.class);
            List<User> users = userMapper.selectAllUser();
            for (User user : users) {
                System.out.println(user);
            }
        }
    }
    

           ②、运行结果

    image

  • 相关阅读:
    微信小程序 | 小程序的转发问题
    开发辅助 | 前端开发工程师必懂的 UI 知识
    微信小程序 | canvas绘图
    服务端 | Linux 学习总结 (一)
    移动端适配 | 适配方案总结
    开发工具 | 利用 deployd 搭建个人博客
    1.10 组织好代码文件,要有“用户思维”
    1.9 组织好代码段,让人对它“一见钟情”
    《计算机是怎样跑起来的》读书笔记(1)
    实用网站收藏
  • 原文地址:https://www.cnblogs.com/tanghaorong/p/14019650.html
Copyright © 2020-2023  润新知