• Spring整合Mybatis和Junit小案例(9)


    环境准备

    步骤1:准备数据库

    Mybatis是来操作数据库表,所以先创建一个数据库及表

    create database spring_db character set utf8;
    use spring_db;
    create table tbl_account(
        id int primary key auto_increment,
        name varchar(35),
        money double
    );
    
    insert into tbl_account(name, money) values('lsm', 123.4),('yxy', 123.4);
    
    select * from tbl_account;
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    步骤2:创建项目导入jar包

    <dependencies>
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-contextartifactId>
            <version>5.2.10.RELEASEversion>
        dependency>
        <dependency>
            <groupId>com.alibabagroupId>
            <artifactId>druidartifactId> 
            <version>1.1.16version>
        dependency>
        <dependency>
            <groupId>org.mybatisgroupId>
            <artifactId>mybatisartifactId>
            <version>3.5.6version>
        dependency>
        <dependency>
            <groupId>mysqlgroupId>
            <artifactId>mysql-connector-javaartifactId>
            <version>5.1.47version>
        dependency>
    dependencies>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22

    步骤3:根据数据库的表创建模型类

    import java.io.Serializable;
    
    public class Account implements Serializable {
        private Integer id;
        private String name;
        private Double money;
    
        public Account() {
        }
    
        public Account(Integer id, String name, Double money) {
            this.id = id;
            this.name = name;
            this.money = money;
        }
    
        public Integer getId() {
            return id;
        }
    
        public void setId(Integer id) {
            this.id = id;
        }
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        public Double getMoney() {
            return money;
        }
    
        public void setMoney(Double money) {
            this.money = money;
        }
    
        @Override
        public String toString() {
            return "Account{" +
                    "id=" + id +
                    ", name='" + name + '\'' +
                    ", money=" + money +
                    '}';
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50

    步骤4:创建Dao接口

    import com.itheima.domain.Account;
    import org.apache.ibatis.annotations.Delete;
    import org.apache.ibatis.annotations.Insert;
    import org.apache.ibatis.annotations.Select;
    import org.apache.ibatis.annotations.Update;
    
    import java.util.List;
    
    public interface AccountDao {
        /**
         * 插入数据到account表中
         * @param account
         */
        @Insert("insert into tbl_account(name, money) values(#{name}, #{money})")
        void save(Account account);
    
        /**
         * 根据id删除数据
         * @param id
         */
        @Delete("delete from tbl_account where id = #{id}}")
        void delete(Integer id);
    
        /**
         * 根据id更新数据
         * @param account
         */
        @Update("update tbl_account set name = #{name}, money = #{money} where id = #{id}")
        void update(Account account);
    
        /**
         * 查找表中的所有数据
         * @return
         */
        @Select("select * from tbl_account")
        List<Account> findAll();
    
        /**
         * 根据id查找数据
         * @param id
         * @return
         */
        @Select("select * from tbl_account where id = #{id}")
        Account findById(Integer id);
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46

    步骤5:创建Service接口和实现类

    service接口

    package com.itheima.service;
    import com.itheima.domain.Account;
    import java.util.List;
    
    
    public interface AccountService {
    
        /**
         * 插入数据到account表中
         * @param account
         */
        void save(Account account);
    
        /**
         * 根据id删除数据
         * @param id
         */
        void delete(Integer id);
    
        /**
         * 根据id更新数据
         * @param account
         */
        void update(Account account);
    
        /**
         * 查找表中的所有数据
         * @return
         */
        List<Account> findAll();
    
        /**
         * 根据id查找数据
         * @param id
         * @return
         */
        Account findById(Integer id);
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39

    service接口的实现类

    package com.itheima.service.impl;
    
    import com.itheima.dao.AccountDao;
    import com.itheima.domain.Account;
    import com.itheima.service.AccountService;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;
    
    import java.util.List;
    
    @Service
    public class AccountServiceImpl implements AccountService {
        @Autowired
        private AccountDao accountDao;
    
        @Override
        public void save(Account account) {
            accountDao.save(account);
        }
    
        @Override
        public void delete(Integer id) {
            accountDao.delete(id);
        }
    
        @Override
        public void update(Account account) {
            accountDao.update(account);
        }
    
        @Override
        public List<Account> findAll() {
            return accountDao.findAll();
        }
    
        @Override
        public Account findById(Integer id) {
            return accountDao.findById(id);
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41

    步骤6:添加jdbc.properties文件

    jdbc.driver=com.mysql.jdbc.Driver
    jdbc.url=jdbc:mysql://localhost:3306/spring_db?useSSL=false&useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT%2B8
    jdbc.username=root
    jdbc.password=1234
    
    • 1
    • 2
    • 3
    • 4

    步骤7:添加Mybatis核心配置文件

    
    DOCTYPE configuration
            PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
            "http://mybatis.org/dtd/mybatis-3-config.dtd">
    <configuration>
        <properties resource="jdbc.properties">properties>
        <typeAliases>
            <package name="com.itheima.domain"/>
        typeAliases>
        <environments default="mysql">
            <environment id="mysql">
                <transactionManager type="JDBC">transactionManager>
                <dataSource type="POOLED">
                    <property name="driver" value="${jdbc.driver}">property>
                    <property name="url" value="${jdbc.url}">property>
                    <property name="username" value="${jdbc.username}">property>
                    <property name="password" value="${jdbc.password}">property>
                dataSource>
            environment>
        environments>
        <mappers>
            <package name="com.itheima.dao">package>
        mappers>
    configuration>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24

    步骤8:编写应用程序

    public class App {
        public static void main(String[] args) throws IOException {
            // 1. 创建SqlSessionFactoryBuilder对象
            SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
            // 2. 加载配置文件
            InputStream inputStream = Resources.getResourceAsStream("SqlMapConfig.xml");
            // 3. 创建SqlSessionFactory对象
            SqlSessionFactory factory = sqlSessionFactoryBuilder.build(inputStream);
            System.out.println(factory);
            // 4. 获取session
            SqlSession sqlSession = factory.openSession();
            System.out.println(sqlSession);
            // 5. 执行sqlSession对象查询,获取结果
            AccountDao accountDao = sqlSession.getMapper(AccountDao.class);
    
            Account account = accountDao.findById(2);
            System.out.println(account);
    
            Account account1 = new Account();
            account1.setName("lsxy");
            account1.setMoney(110.0);
            accountDao.save(account1);
    
            List<Account> all = accountDao.findAll();
            System.out.println(all);
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28

    步骤9:运行程序

    在这里插入图片描述

    Spring整合Mybatis

    整合Mybatis思路

    • Mybatis程序核心对象分析, 从下图可知,真正需要交给Spring管理的是SqlSessionFactory

    在这里插入图片描述

    • 整合Mybatis,就是将Mybatis用到的内容交给Spring管理,分析下配置文件
      在这里插入图片描述

    说明:

    • 第一行读取外部properties配置文件,Spring有提供具体的解决方案@PropertySource,需要交给Spring
    • 第二行起别名包扫描,为SqlSessionFactory服务的,需要交给Spring
    • 第三行主要用于做连接池,Spring之前我们已经整合了Druid连接池,这块也需要交给Spring
    • 前面三行一起都是为了创建SqlSession对象用的,那么用Spring管理SqlSession对象吗?回忆下SqlSession是由SqlSessionFactory创建出来的,所以只需要将SqlSessionFactory交给Spring管理即可。
    • 第四行是Mapper接口和映射文件[如果使用注解就没有该映射文件],这个是在获取到SqlSession以后执行具体操作的时候用,所以它和SqlSessionFactory创建的时机都不在同一个时间,可能需要单独管理

    步骤1:项目中导入整合需要的jar包

    <dependency>
        
        <groupId>org.springframeworkgroupId>
        <artifactId>spring-jdbcartifactId>
        <version>5.2.10.RELEASEversion>
    dependency>
    <dependency>
        
        <groupId>org.mybatisgroupId>
        <artifactId>mybatis-springartifactId>
        <version>1.3.0version>
    dependency>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    步骤2:创建Spring的主配置类

    // 配置类注解
    @Configuration
    @ComponentScan("com.itheima")
    public class SpringConfig {
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5

    步骤3:创建Jdbc数据源的配置类

    在配置类中完成数据源的创建

    import com.alibaba.druid.pool.DruidDataSource;
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.context.annotation.Bean;
    import javax.sql.DataSource;
    
    public class JdbcConfig {
        @Value("${jdbc.driver}")
        private String diverName;
        
        @Value("${jdbc.url}")
        private String url;
        
        @Value("${jdbc.username}")
        private String username;
        
        @Value("${jdbc.password}")
        private String password;
    
        @Bean
        public DataSource getDataSource() {
            DruidDataSource druidDataSource = new DruidDataSource();
            druidDataSource.setDriverClassName(diverName);
            druidDataSource.setUrl(url);
            druidDataSource.setPassword(password);
            druidDataSource.setUsername(username);
            return druidDataSource;
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29

    步骤4: 主配置类中读properties并引入数据源配置类

    @Configuration  // 配置类注解
    @ComponentScan("com.itheima")  // 包扫描,主要扫描的是醒目中的AccountServiceImpl类
    @Import({JdbcConfig.class})
    //@PropertySource({"jdbc.properties"})
    @PropertySource("jdbc.properties")
    public class SpringConfig {
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    步骤5: 创建Mybatis配置类并配置SqlSessionFactory(整合时的关键模板,再整合的时候可以直接进行引用)

    import org.mybatis.spring.SqlSessionFactoryBean;
    import org.mybatis.spring.mapper.MapperScannerConfigurer;
    import org.springframework.context.annotation.Bean;
    
    import javax.sql.DataSource;
    
    
    // 对应SqlMapConfig.xml文件
    public class MybatisConfig {
        @Bean
        public SqlSessionFactoryBean sqlSessionFactory(DataSource dataSource){
            SqlSessionFactoryBean ssfb = new SqlSessionFactoryBean();
            /**
             * 对应
             *  
             *         
             *  
             */
            ssfb.setTypeAliasesPackage("com.itheima.domain");
            /**
             * 对应
             *  
             *                 
             *                 
             *                 
             *                 
             *  
             */
            ssfb.setDataSource(dataSource);
            return ssfb;
        }
    
        @Bean
        public MapperScannerConfigurer mapperScannerConfigurer(){
            MapperScannerConfigurer msc = new MapperScannerConfigurer();
            msc.setBasePackage("com.itheima.dao");
            return msc;
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40

    说明:

    • 使用SqlSessionFactoryBean封装SqlSessionFactory需要的环境信息
      在这里插入图片描述

      • SqlSessionFactoryBean是前面我们讲解FactoryBean的一个子类,在该类中将SqlSessionFactory的创建进行了封装,简化对象的创建,我们只需要将其需要的内容设置即可。
      • 方法中有一个参数为dataSource,当前Spring容器中已经创建了Druid数据源,类型刚好是DataSource类型,此时在初始化SqlSessionFactoryBean这个对象的时候,发现需要使用DataSource对象,而容器中刚好有这么一个对象,就自动加载了DruidDataSource对象。
    • 使用MapperScannerConfigurer加载Dao接口,创建代理对象保存到IOC容器中
      在这里插入图片描述

      • 这个MapperScannerConfigurer对象也是MyBatis提供的专用于整合的jar包中的类,用来处理原始配置文件中的mappers相关配置,加载数据层的Mapper接口类
      • MapperScannerConfigurer有一个核心属性basePackage,就是用来设置所扫描的包路径

    步骤6: 主配置类中引入Mybatis配置类

    @Configuration  // 配置类注解
    @ComponentScan("com.itheima")  // 包扫描,主要扫描的是醒目中的AccountServiceImpl类
    @Import({JdbcConfig.class, MybatisConfig.class})
    //@PropertySource({"jdbc.properties"})
    @PropertySource("jdbc.properties")
    public class SpringConfig {
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    步骤7:编写运行类并运行

    public class App2 {
        public static void main(String[] args) {
            ApplicationContext act = new AnnotationConfigApplicationContext(SpringConfig.class);
            AccountServiceImpl accountService = act.getBean(AccountServiceImpl.class);
            List<Account> accountList = accountService.findAll();
            System.out.println(accountList);
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    在这里插入图片描述

    Sprin整合Junit

    在上述环境的基础上,我们来对Junit进行整合。

    步骤1:引入Junit依赖

     <dependency>
                <groupId>junitgroupId>
                <artifactId>junitartifactId>
                <version>4.12version>
                <scope>testscope>
            dependency>
    
            <dependency>
                <groupId>org.springframeworkgroupId>
                <artifactId>spring-testartifactId>
                <version>5.2.10.RELEASEversion>
            dependency>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    步骤2:编写测试类

    //设置类运行器
    @RunWith(SpringJUnit4ClassRunner.class)
    //设置Spring环境对应的配置类
    @ContextConfiguration(classes = {SpringConfig.class}) //加载配置类
    public class AccountServiceTest {
        //支持自动装配注入bean
        @Autowired
        private AccountService accountService;
        @Test
        public void testFindById(){
            System.out.println(accountService.findById(1));
    
        }
        @Test
        public void testFindAll(){
            System.out.println(accountService.findAll());
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18

    注意:

    • 单元测试,如果测试的是注解配置类,则使用@ContextConfiguration(classes = 配置类.class)
    • 单元测试,如果测试的是配置文件,则使用@ContextConfiguration(locations={配置文件名,...})
    • Junit运行后是基于Spring环境运行的,所以Spring提供了一个专用的类运行器,这个务必要设置,这个类运行器就在Spring的测试专用包中提供的,导入的坐标就是这个东西SpringJUnit4ClassRunner
    • 上面两个配置都是固定格式,当需要测试哪个bean时,使用自动装配加载对应的对象,下面的工作就和以前做Junit单元测试完全一样了
  • 相关阅读:
    Docker安装入门教程
    10年内取代iPhone,目标10亿用户,苹果押注AR头戴设备
    数据结构-二叉树的基本操作
    AtCoder—C - ABC conjecture
    软件工程考试题目:结构化方法的基本原则是功能的分解和 抽象,建立以下有关“微机”的对象模型,JACKSON的结构描述问题的输入和输出的数据结构
    5分钟带你了解python中超级好用的库 you-get
    大都会人寿线下培训第三天回顾(爱的书信)及线上课程笔记
    【FPGA】zynq 单端口RAM 双端口RAM 读写冲突 写写冲突
    记一次密码控制功能
    计算机的错误计算(五十七)
  • 原文地址:https://blog.csdn.net/qq_43751200/article/details/127905141