• 整合MyBatis



    学习视频来自于:秦疆(遇见狂神说)Bilibili地址
    他的自学网站:kuangstudy

    但行好事,莫问前程


    一、整合MyBatis

    1.1 相关jar包

    • junit
    • mybatis
    • mysql数据库
    • spring相关
    • aop织入器
    • mybatis-spring整合包重点
    • 在此还可以导入了lombok包,不导入也可以(看你喜不喜欢用)
    • 连接池用不用都可以
    <dependency>
        <groupId>junitgroupId>
        <artifactId>junitartifactId>
        <version>4.12version>
        <scope>testscope>
    dependency>
    <dependency>
        <groupId>org.mybatisgroupId>
        <artifactId>mybatisartifactId>
        <version>3.5.10version>
    dependency>
    <dependency>
        <groupId>mysqlgroupId>
        <artifactId>mysql-connector-javaartifactId>
        <version>8.0.29version>
    dependency>
    <dependency>
        <groupId>org.springframeworkgroupId>
        <artifactId>spring-webmvcartifactId>
        <version>5.3.22version>
    dependency>
    <dependency>
        <groupId>org.springframeworkgroupId>
        <artifactId>spring-jdbcartifactId>
        <version>5.3.22version>
    dependency>
    <dependency>
        <groupId>org.aspectjgroupId>
        <artifactId>aspectjweaverartifactId>
        <version>1.9.9.1version>
    dependency>
    <dependency>
        <groupId>org.mybatisgroupId>
        <artifactId>mybatis-springartifactId>
        <version>2.0.7version>
    dependency>
    <dependency>
        <groupId>com.alibabagroupId>
        <artifactId>druidartifactId>
        <version>1.2.11version>
    dependency>
    
    • 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

    配置Maven静态资源过滤问题!

    <build>
        
        <resources>
            <resource>
                <directory>src/main/javadirectory>
                <includes>
                    <include>**/*.propertiesinclude>
                    <include>**/*.xmlinclude>
                includes>
                <filtering>falsefiltering>
            resource>
            <resource>
                <directory>src/main/resourcesdirectory>
                <includes>
                    <include>**/*.propertiesinclude>
                    <include>**/*.xmlinclude>
                includes>
                <filtering>falsefiltering>
            resource>
        resources>
    build>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21

    1.2 回忆mybatis

    1. 数据库8.0版本,创建数据库mybatis
    SET NAMES utf8mb4;
    SET FOREIGN_KEY_CHECKS = 0;
    
    -- ----------------------------
    -- Table structure for blog
    -- ----------------------------
    DROP TABLE IF EXISTS `blog`;
    CREATE TABLE `blog`  (
      `id` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '博客id',
      `title` varchar(100) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '博客标题',
      `author` varchar(30) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '博客作者',
      `create_time` datetime NOT NULL COMMENT '创建时间',
      `views` int NOT NULL COMMENT '浏览量',
      PRIMARY KEY (`id`) USING BTREE
    ) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
    
    -- ----------------------------
    -- Records of blog
    -- ----------------------------
    INSERT INTO `blog` VALUES ('0a547141ea664a438268c8f20e5dd049', 'Spring如此简单', '狂神过', '2022-07-30 17:11:20', 9999);
    INSERT INTO `blog` VALUES ('0e4cd725e18549cca0fb7fba317fb82a', '微服务如此简单', '狂神过', '2022-07-30 17:11:20', 9999);
    INSERT INTO `blog` VALUES ('146474f0cb1349369d345285b46e0205', 'Mybatis如此简单', '狂神过', '2022-07-30 17:11:19', 1000);
    INSERT INTO `blog` VALUES ('2e08249e74d44b12910f16986b49fcd5', 'Java如此简单', '狂神过', '2022-07-30 17:11:20', 9999);
    
    SET FOREIGN_KEY_CHECKS = 1;
    
    • 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
    1. 编写pojo实体类
    public class Blog {
        private String id;
        private String title;
        private String author;
        private Date createTime;
        private int views;
    
        public String getId() {
            return id;
        }
    
        public void setId(String id) {
            this.id = id;
        }
    
        public String getTitle() {
            return title;
        }
    
        public void setTitle(String title) {
            this.title = title;
        }
    
        public String getAuthor() {
            return author;
        }
    
        public void setAuthor(String author) {
            this.author = author;
        }
    
        public Date getCreateTime() {
            return createTime;
        }
    
        public void setCreateTime(Date createTime) {
            this.createTime = createTime;
        }
    
        public int getViews() {
            return views;
        }
    
        public void setViews(int views) {
            this.views = views;
        }
    
        @Override
        public String toString() {
            return "Blog{" +
                    "id='" + id + '\'' +
                    ", title='" + title + '\'' +
                    ", author='" + author + '\'' +
                    ", createTime=" + createTime +
                    ", views=" + views +
                    '}';
        }
    }
    
    • 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
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    1. 编写实现mybatis的配置文件

    druid.properties

    druid.driverClassName=com.mysql.cj.jdbc.Driver
    druid.url=jdbc:mysql://localhost:3306/mybatis?userUnicode=true&characterEncoding=utf8&useSSL=true&serverTime=GMT%2B8
    druid.username=root
    druid.password=root
    
    • 1
    • 2
    • 3
    • 4

    使用连接池需要写数据源适配器DruidDataSourceFactory

    public class DruidDataSourceFactory extends UnpooledDataSourceFactory {
        public DruidDataSourceFactory() {
            this.dataSource = new DruidDataSource();
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5

    mybatis-config.xml

    
    DOCTYPE configuration
            PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
            "http://mybatis.org/dtd/mybatis-3-config.dtd">
    <configuration>
        <properties resource="druid.properties"/>
        <settings>
            <setting name="logImpl" value="STDOUT_LOGGING"/>
            <setting name="mapUnderscoreToCamelCase" value="true"/>
        settings>
        <typeAliases>
            <package name="pers.tianyu.pojo"/>
        typeAliases>
        <environments default="druidDataSource">
            <environment id="druidDataSource">
                <transactionManager type="JDBC"/>
                <dataSource type="pers.tianyu.utils.DruidDataSourceFactory">
                    <property name="driverClassName" value="${driverClassName}"/>
                    <property name="url" value="${url}"/>
                    <property name="username" value="${username}"/>
                    <property name="password" value="${password}"/>
                dataSource>
            environment>
        environments>
        <mappers>
            <mapper resource="pers/tianyu/dao/BlogMapper.xml"/>
        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
    • 25
    • 26
    • 27
    • 28
    1. 编写BlogMapper接口
    public interface BlogMapper {
        public int insertByBlog(Blog blog);
    
        public int deleteById(int id);
    
        public int updateByBlog(Blog blog);
    
        public List<Blog> queryBlog();
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    1. 编写BlogMapper.xml文件
    
    DOCTYPE mapper
            PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
            "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    <mapper namespace="pers.tianyu.dao.BlogMapper">
        <select id="queryBlog" resultType="blog">
            select * from Blog
        select>
    mapper>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    1. 测试
    @Test
    public void queryBlogTest() throws IOException {
        String resource = "mybatis-config.xml";
        InputStream stream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(stream);
        SqlSession sqlSession = sqlSessionFactory.openSession();
        
        BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
        
        for (Blog blog : mapper.queryBlog()) {
            System.out.println(blog);
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    1.3 Mybatis-Spring

    1.3.1 介绍

    MyBatis-Spring 会帮助你将 MyBatis 代码无缝地整合到 Spring 中。
    文档链接
    如果使用 Maven 作为构建工具,仅需要在 pom.xml 中加入以下代码即可:

    <dependency>
        <groupId>org.mybatisgroupId>
        <artifactId>mybatis-springartifactId>
        <version>2.0.7version>
    dependency>
    
    • 1
    • 2
    • 3
    • 4
    • 5

    1.3.2 整合实现一

    1. 创建Spring配置文件spring-dao.xml
    
    <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
            https://www.springframework.org/schema/beans/spring-beans.xsd
            http://www.springframework.org/schema/context
            https://www.springframework.org/schema/context/spring-context.xsd">
    
         
    beans>   
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    1. 配置数据源替换mybaits的数据源

    方式一:引入druid.properties文件

    
    <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="location" value="classpath:druid.properties"/>
    bean>
    
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="${druid.driverClassName}"/>
        <property name="url" value="${druid.url}"/>
        <property name="username" value="${druid.username}"/>
        <property name="password" value="${druid.password}"/>
    bean>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    方式二:引入druid.properties文件

    
    <context:property-placeholder location="classpath:druid.properties"/>
    
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="${druid.driverClassName}"/>
        <property name="url" value="${druid.url}"/>
        <property name="username" value="${druid.username}"/>
        <property name="password" value="${druid.password}"/>
    bean>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    方式三:引入druid.properties文件

    
    <bean id="configProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
    <property name="location" value="classpath:druid.properties"/>
    bean>
    
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
    <property name="driverClassName">
            <value>#{configProperties['druid.driverClassName']}value>
        property>
        <property name="url">
            <value>#{configProperties['druid.url']}value>
        property>
        <property name="username">
            <value>#{configProperties['druid.username']}value>
        property>
        <property name="password">
            <value>#{configProperties['druid.password']}value>
        property>
    bean>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19

    如果druid.properties内名称格式不是 名字.名字(druid.password) 就会出现错误,有没有懂得讲一讲,学习一下。

    1. 配置SqlSessionFactory,关联MyBatis
    
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
        
    bean>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    1. 注册sqlSessionTemplate,关联sqlSessionFactory
    
    <bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">
        
        <constructor-arg name="sqlSessionFactory" ref="sqlSessionFactory"/>
    bean>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    1. 将配置引入applicationContext.xml中
    
    <import resource="spring-dao.xml"/>
    
    • 1
    • 2
    1. 需要UserMapper接口的UserMapperImpl 实现类,私有化sqlSessionTemplate
    public class BlogMapperImpl implements BlogMapper {
    
        // 在原来我们的所有操作,都使用sqlSession来执行,现在都使用SqlSessionTemplate,
        // 现在使用sqlSessionTemplate,这两个本质一样。
        private SqlSessionTemplate sqlSessionTemplate;
    
        public void setSqlSessionTemplate(SqlSessionTemplate sqlSessionTemplate) {
            this.sqlSessionTemplate = sqlSessionTemplate;
        }
    
        @Override
        public int insertByBlog(Blog blog) {
            return 0;
        }
    
        @Override
        public int deleteById(int id) {
            return 0;
        }
    
        @Override
        public int updateByBlog(Blog blog) {
            return 0;
        }
    
        @Override
        public List<Blog> queryBlog() {
            BlogMapper mapper = sqlSessionTemplate.getMapper(BlogMapper.class);
            return mapper.queryBlog();
        }
    }
    
    • 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
    1. 将自己写的实现类,注册到applicationContext.xml配置文件中。
    
    <bean id="blogMapper" class="pers.tianyu.dao.BlogMapperImpl">
        <property name="sqlSessionTemplate" ref="sqlSessionTemplate"/>
    bean>
    
    • 1
    • 2
    • 3
    • 4
    1. 测试使用即可!
    @Test
    public void queryBlogSpringTest1(){
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        BlogMapperImpl blogMapper = context.getBean("blogMapper", BlogMapperImpl.class);
        for (Blog blog : blogMapper.queryBlog()) {
            System.out.println(blog);
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    1.3.3 整合实现二

    mybatis-spring1.2.3版以上的才有这个,官方文档截图:

    dao继承Support类 , 直接利用 getSqlSession() 获得 , 然后直接注入SqlSessionFactory . 比起整合方式一 , 不需要管理SqlSessionTemplate , 而且对事务的支持更加友好 . 可跟踪源码查看。
    在这里插入图片描述

    1. 将我们上面写的UserMapperImpl修改一下
    public class BlogMapperImpl2 extends SqlSessionDaoSupport implements BlogMapper {
    
        @Override
        public int insertByBlog(Blog blog) {
            return 0;
        }
    
        @Override
        public int deleteById(int id) {
            return 0;
        }
    
        @Override
        public int updateByBlog(Blog blog) {
            return 0;
        }
    
        @Override
        public List<Blog> queryBlog() {
        	// 不需要在传进来SqlSessionTemplate,使用getSqlSession()方法获取就可以了。
            BlogMapper mapper = getSqlSession().getMapper(BlogMapper.class);
            return mapper.queryBlog();
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    1. 注册到applicationContext.xml配置文件中。
    
    <bean id="blogMapper2" class="pers.tianyu.dao.BlogMapperImpl2">
        <property name="sqlSessionFactory" ref="sqlSessionFactory"/>
    bean>
    
    • 1
    • 2
    • 3
    • 4
    1. 测试使用即可!
     @Test
     public void queryBlogSpringTest2(){
         ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
         BlogMapperImpl2 blogMapper = context.getBean("blogMapper2", BlogMapperImpl2.class);
         for (Blog blog : blogMapper.queryBlog()) {
             System.out.println(blog);
         }
     }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
  • 相关阅读:
    设计模式——创建型设计模式
    深入理解函数式编程(上)
    《RISC-V体系结构编程与实践》的benos_payload程序——mysbi跳转到benos分析
    PgSQL-执行器机制-Unique算子
    Difference quotient
    Amlogic T972 AOSP 编译服务器搭建
    深入理解数据库原理
    15 个实用的 Linux find 命令示例
    华纳云:Linux每天自动备份mysql数据库怎么实现
    按键控制LED灯亮灭
  • 原文地址:https://blog.csdn.net/zhao854116434/article/details/126307735