• 【狂神说Java】SpringBoot笔记——整合数据库


    SpringBoot整合数据库

    前言:关于本节的问题汇总

    遇到问题可参考下面文章内容
    https://blog.csdn.net/qq_58233406/article/details/126914605
    在这里插入图片描述

    1、整合JDBC

    1.1、SpringData简介

    • 对于数据访问层,无论是 SQL(关系型数据库) 还是 NOSQL(非关系型数据库),Spring Boot 底层都是采用 Spring Data 的方式进行统一处理。
    • Spring Boot 底层都是采用 Spring Data 的方式进行统一处理各种数据库,Spring Data 也是 Spring 中与 Spring Boot、Spring Cloud 等齐名的知名项目。
    • Sping Data 官网:https://spring.io/projects/spring-data
    • 数据库相关的启动器 :弹簧启动参考文档 (spring.io)(2.7.3)

    在这里插入图片描述

    1.2、整合JDBC

    • 导入测试数据库
    CREATE DATABASE /*!32312 IF NOT EXISTS*/`springboot` /*!40100 DEFAULT
    CHARACTER SET utf8 */;
    
    USE `springboot`;
    
    /*Table structure for table `department` */
    DROP TABLE IF EXISTS `department`;
    
    CREATE TABLE `department` (
    `id` int(3) NOT NULL AUTO_INCREMENT COMMENT '部门id',
    `department_name` varchar(20) NOT NULL COMMENT '部门名字',
    PRIMARY KEY (`id`)
    ) ENGINE=InnoDB AUTO_INCREMENT=106 DEFAULT CHARSET=utf8;
    /*Data for the table `department` */
    
    insert into `department`(`id`,`department_name`) values (101,'技术部'),
    (102,'销售部'),(103,'售后部'),(104,'后勤部'),(105,'运营部');
    
    /*Table structure for table `employee` */
    DROP TABLE IF EXISTS `employee`;
    
    CREATE TABLE `employee` (
    `id` int(5) NOT NULL AUTO_INCREMENT COMMENT '雇员id',
    `last_name` varchar(100) NOT NULL COMMENT '名字',
    `email` varchar(100) NOT NULL COMMENT '邮箱',
    `gender` int(2) NOT NULL COMMENT '性别1 男, 0 女',
    `department` int(3) NOT NULL COMMENT '部门id',
    `birth` datetime NOT NULL COMMENT '生日',
    PRIMARY KEY (`id`)
    ) ENGINE=InnoDB AUTO_INCREMENT=1006 DEFAULT CHARSET=utf8;
    /*Data for the table `employee` */
    
    insert into
    `employee`(`id`,`last_name`,`email`,`gender`,`department`,`birth`) values
    (1001,'张三','243357594@qq.com',1,101,'2021-03-06 15:04:33'),(1002,'李
    四','243357594@qq.com',1,102,'2021-03-06 15:04:36'),(1003,'王
    五','243357594@qq.com',0,103,'2021-03-06 15:04:37'),(1004,'赵
    六','243357594@qq.com',1,104,'2021-03-06 15:04:39'),(1005,'孙
    七','243357594@qq.com',0,105,'2021-03-06 15:04:45');
    
    • 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
    • 新建一个项目测试:SpringBoot-06-data

    在这里插入图片描述

    • 项目建好之后,发现自动帮我们导入了如下的启动器:
    <dependencies>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-jdbcartifactId>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-webartifactId>
        dependency>
    
        <dependency>
            <groupId>mysqlgroupId>
            <artifactId>mysql-connector-javaartifactId>
            <scope>runtimescope>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-testartifactId>
            <scope>testscope>
        dependency>
    dependencies>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 编写yaml配置文件连接数据库(本人Mysql版本为5.1.47)
    spring:
      datasource:
        username: root
        password: 1234
        url: jdbc:mysql://localhost:3306/ssmbuild?useSSL=true&useUnicode=true&characterEncoding=utf8
        driver-class-name: com.mysql.jdbc.Driver
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    补充:Mysql8.0版本为如下配置

    spring: 
      datasource:
        username: root
        password: 1234
        # ?serverTimezone=UTC解决时区的报错
        url: jdbc:mysql://localhost:3306/springboot?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
        driver-class-name: com.mysql.cj.jdbc.Driver
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 测试
    package com.example.springboot06data;
    
    import org.junit.jupiter.api.Test;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.boot.test.context.SpringBootTest;
    
    import javax.sql.DataSource;
    import java.sql.Connection;
    import java.sql.SQLException;
    
    
    @SpringBootTest
    class SpringBoot06DataApplicationTests {
        @Autowired
        DataSource dataSource;
    
        @Test
        void contextLoads() throws SQLException {
            // 查看默认数据源
            System.out.println(dataSource.getClass());
            // 获得连接
            Connection connection = dataSource.getConnection();
            System.out.println(connection);
            // 关闭连接
            connection.close();
        }
    
    }
    
    • 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

    在这里插入图片描述

    可以看到:默认数据源为 class com.zaxxer.hikari.HikariDataSource

    补充:如果datasource报错,就降低springboot版本,我原本使用的2.7.3虽然报红线但是还可以使用,不想报红线可以降低版本为2.6.11

    在这里插入图片描述

    1.3、分析源码

    全局搜索:DataSourceAutoConfiguration文件

    @Import({Hikari.class, Tomcat.class, Dbcp2.class, OracleUcp.class, Generic.class, DataSourceJmxConfiguration.class})
    protected static class PooledDataSourceConfiguration {
        protected PooledDataSourceConfiguration() {
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 这里导入的类都在 DataSourceConfiguration 配置类下,可以看出 Spring Boot 2.6.3默认使用 HikariDataSource 数据源,而以前版本,如 Spring Boot 1.5默认使用 org.apache.tomcat.jdbc.pool.DataSource 作为数据源;
    • HikariDataSource 号称 Java WEB 当前速度最快的数据源,相比于传统的 C3P0 、DBCP、Tomcat jdbc 等连接池更加优秀;
    • 可以使用 spring.datasource.type 指定自定义的数据源类型,值为要使用的连接池实现的完全限定名
    • 关于数据源不做过多介绍,有了数据库连接,显然就可以CRUD操作数据库了。但是仍需要先了解一个对象——JdbcTemplate

    1.4、JdbcTemplate

    1. 有了数据源(com.zaxxer.hikari.HikariDataSource),然后可以拿到数据库连接 (java.sql.Connection),有了连接,就可以使用原生的 JDBC 语句来操作数据库;
    2. 即使不使用第三方第数据库操作框架,如 MyBatis等,Spring 本身也对原生的JDBC 做了轻量级的封装,即JdbcTemplate
    3. 数据库操作的所有 CRUD 方法都在 JdbcTemplate 中。
    4. Spring Boot不仅提供了默认的数据源,同时默认已经配置好了 JdbcTemplate 放在了容器中,程序员只需自己注入即可使用。
    5. JdbcTemplate 的自动配置是依赖 org.springframework.boot.autoconfigure.jdbc 包下的JdbcTemplateConfiguration类。

    在这里插入图片描述

    JdbcTemplate主要提供以下几类方法

    • execute方法:可以用于执行任何SQL语句,一般用于执行DDL语句;
    • update方法及batchUpdate方法:update方法用于执行新增、修改、删除等语句;batchUpdate 方法用于执行批处理相关语句;
    • query方法及queryForXXX方法:用于执行查询相关语句;
    • call方法:用于执行存储过程、函数相关语句。

    在这里插入图片描述

    1.5、增删改查案例

    • 查询
    /**
      *     查询employee表中所有数据
      *     List 中的1个 Map 对应数据库的 1行数据
      *     Map 中的 key 对应数据库的字段名,value 对应数据库的字段值
      */
    @GetMapping("/list")
    public  List<Map<String,Object>> userList() {
        String sql = "select * from employee";
        List<Map<String,Object>> maps = jdbcTemplate.queryForList(sql);
        return maps;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    在这里插入图片描述

    • 增加员工
    /**
         *  增加员工
         */
    @GetMapping("/add")
    public int add(){
        //new Date().toLocaleString默认设置为12小时,会显示上午、下午.可设置为24小时var time=new Date().toLocaleString('chinese',{hour12:false});
        String sql = "insert into employee(`last_Name`,`email`,`gender`,`department`,`birth`) values('BoBooY','123456789@qq.com',1,105,'" + new Date().toLocaleString()+"')";
    
        int updateRows = jdbcTemplate.update(sql);
        return updateRows;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 修改员工
    /**
         *  修改员工
         */
    @GetMapping("/update/{id}")
    public int update(@PathVariable("id") int id) {
        String sql = "update employee set last_Name=?,email=? where id=" + id;
        Object[] data = new Object[2];
        data[0] = "BoBooY";
        data[1] = "123456789@qq.com";
        int updateRows = jdbcTemplate.update(sql,data);
        return updateRows;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 删除员工
    /**
         *  删除员工
         */
    @GetMapping("/delete/{id}")
    public int delete(@PathVariable("id") int id) {
        String sql = "delete from employee where id="+ id;
        int updateRows = jdbcTemplate.update(sql);
        return updateRows;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 完整代码(JdbcController
    package com.example.springboot06data.controller;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.jdbc.core.JdbcTemplate;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.PathVariable;
    import org.springframework.web.bind.annotation.RestController;
    
    import java.util.Date;
    import java.util.List;
    import java.util.Map;
    
    /**
     * @author BoBooY
     * @date 2022/9/14 21:44
     */
    @RestController
    public class JdbcController {
        /**
         *  Spring Boot 默认提供了数据源,默认提供了 org.springframework.jdbc.core.JdbcTemplate
         *  JdbcTemplate 中会自己注入数据源,用于简化 JDBC操作
         *  还能避免一些常见的错误,使用起来也不用再自己来关闭数据库连接
         */
        @Autowired
        JdbcTemplate jdbcTemplate;
    
        /**
         *     查询employee表中所有数据
         *     List 中的1个 Map 对应数据库的 1行数据
         *     Map 中的 key 对应数据库的字段名,value 对应数据库的字段值
         */
        @GetMapping("/list")
        public  List<Map<String,Object>> userList() {
            String sql = "select * from employee";
            List<Map<String,Object>> maps = jdbcTemplate.queryForList(sql);
            return maps;
        }
    
        /**
         *  增加员工
         */
        @GetMapping("/add")
        public int add(){
            //new Date().toLocaleString默认设置为12小时,会显示上午、下午.可设置为24小时var time=new Date().toLocaleString('chinese',{hour12:false});
           String sql = "insert into employee(`last_Name`,`email`,`gender`,`department`,`birth`) values('BoBooY','123456789@qq.com',1,105,'" + new Date().toLocaleString()+"')";
    
            int updateRows = jdbcTemplate.update(sql);
            return updateRows;
        }
    
        /**
         *  修改员工
         */
        @GetMapping("/update/{id}")
        public int update(@PathVariable("id") int id) {
            String sql = "update employee set last_Name=?,email=? where id=" + id;
            Object[] data = new Object[2];
            data[0] = "BoBooY";
            data[1] = "123456789@qq.com";
            int updateRows = jdbcTemplate.update(sql,data);
            return updateRows;
        }
    
        /**
         *  删除员工
         */
        @GetMapping("/delete/{id}")
        public int delete(@PathVariable("id") int id) {
            String sql = "delete from employee where id="+ id;
            int updateRows = jdbcTemplate.update(sql);
            return updateRows;
        }
    }
    
    • 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
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74

    2、整合Druid

    2.1、Druid简介

    • Java程序很大一部分要操作数据库,为了提高性能操作数据库的时候,又不得不使用数据库连接池。
    • Druid是阿里巴巴开源平台上一个数据库连接池实现,结合了 C3P0、DBCP 等DB池的优点,同时加入了日志监控。
    • Druid可以很好的监控 DB 池连接和 SQL 的执行情况,天生就是针对监控而生的DB连接池。
    • Spring Boot 2.0 以上默认使用Hikari数据源,可以说Hikari与Driud都是当前Java Web上最优秀的数据源,我们来重点介绍Spring Boot如何集成Druid数据源,如何实现数据库监控。
    • Github地址:https://github.com/alibaba/druid

    com.alibaba.druid.pool.DruidDataSource 基本配置参数如下:

    配置缺省值说明
    name配置这个属性的意义在于,如果存在多个数据源,监控的时候可以通过名字来区分开来。如果没有配置,将会生成一个名字,格式是:“DataSource-” + System.identityHashCode(this).
    url连接数据库的url,不同数据库不一样。例如: mysql: jdbc:mysql://10.20.153.104:3306/druid2 oracle: jdbc:oracle:thin:@10.20.149.85:1521:ocnauto
    username连接数据库的用户名
    password连接数据库的密码。如果你不希望密码直接写在配置文件中,可以使用ConfigFilter。
    driverClassName根据url自动识别这一项可配可不配,如果不配置druid会根据url自动识别dbType,然后选择相应的driverClassName
    initalSize0初始化时建立物理连接的个数。初始化发生在显示调用init方法,或者第一次getConnection时
    maxActive8最大连接池数量
    maxIdle8已经不再使用,配置了也没效果
    minIdle最小连接池数量
    maxWait获取连接时最大等待时间,单位毫秒。配置了maxWait之后,缺省启用公平锁,并发效率会有所下降,如果需要可以通过配置useUnfairLock属性为true使用非公平锁。
    poolPreparedStatementsfalse是否缓存preparedStatement,也就是PSCache。PSCache对支持游标的数据库性能提升巨大,比如说oracle。在mysql下建议关闭。
    maxOpenPreparedStatements-1要启用PSCache,必须配置大于0,当大于0时,poolPreparedStatements自动触发修改为true。在Druid中,不会存在Oracle下PSCache占用内存过多的问题,可以把这个数值配置大一些,比如说100
    validationQuery用来检测连接是否有效的sql,要求是一个查询语句。如果validationQuery为null,testOnBorrow、testOnReturn、testWhileIdle都不会其作用。
    validationQueryTimeout单位:秒,检测连接是否有效的超时时间。底层调用jdbc Statement对象的void setQueryTimeout(int seconds)方法。
    testOnBorrowtrue申请连接时执行validationQuery检测连接是否有效,做了这个配置会降低性能。
    testOnReturnfalse归还连接时执行validationQuery检测连接是否有效,做了这个配置会降低性能
    testWhileIdlefalse建议配置为true,不影响性能,并且保证安全性。申请连接的时候检测,如果空闲时间大于timeBetweenEvictionRunsMillis,执行validationQuery检测连接是否有效。
    timeBetweenEvictionRunsMillis1分钟 (1.0.14)有两个含义: 1) Destroy线程会检测连接的间隔时间,如果连接空闲时间大于等于minEvictableIdleTimeMillis则关闭物理连接 2) testWhileIdle的判断依据,详细看testWhileIdle属性的说明。
    numTestsPerEvictionRun不再使用,一个DruidDataSource只支持一个EvictionRun
    numTestsPerEvictionRun30分钟 (1.0.14)连接保持空闲而不被驱逐的最长时间
    connectionInitSqls物理连接初始化的时候执行的sql
    exceptionSorter根据dbType自动识别当数据库抛出一些不可恢复的异常时,抛弃连接
    filters属性类型是字符串,通过别名的方式配置扩展插件,常用 的插件有:监控统计用的filter:stat 日志用的filter:log4j 防御sql注入的filter:wall
    proxyFilters类型是List,如果同时配置了filters和proxyFilters,是组合关系,并非替换关系

    2.2、配置数据源

    • 添加上Druid数据源依赖。
    
    <dependency>
        <groupId>com.alibabagroupId>
        <artifactId>druidartifactId>
        <version>1.2.6version>
    dependency>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 切换数据源,之前已经说过 Spring Boot 2.0 以上默认使用com.zaxxer.hikari.HikariDataSource数据源,但可以通过spring.datasource.type指定数据源。
    spring:
      datasource:
        username: root
        password: root
        # ?serverTimezone=UTC解决时区的报错
        url: jdbc:mysql://localhost:3306/springboot?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
        driver-class-name: com.mysql.cj.jdbc.Driver
        type: com.alibaba.druid.pool.DruidDataSource # 自定义数据源
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 数据源切换之后,在测试类中注入DataSource,然后获取到它,输出一看便知是否成功切换;

    在这里插入图片描述

    • 设置数据源连接初始化大小、最大连接数、等待时间、最小连接数 等设置项,可以查看源码。
    spring:
      datasource:
        username: root
        password: 1234
        url: jdbc:mysql://localhost:3306/springboot?useSSL=true&useUnicode=true&characterEncoding=utf8
        driver-class-name: com.mysql.jdbc.Driver
        type: com.alibaba.druid.pool.DruidDataSource # 自定义数据源
        #数据源
        #Spring Boot 默认是不注入这些属性值的,需要自己绑定
        #druid 数据源专有配置
        initialSize: 5
        minIdle: 5
        maxActive: 20
        maxWait: 60000
        timeBetweenEvictionRunsMillis: 60000
        minEvictableIdleTimeMillis: 300000
        validationQuery: SELECT 1 FROM DUAL
        testWhileIdle: true
        testOnBorrow: false
        testOnReturn: false
        poolPreparedStatements: true
          #配置监控统计拦截的filters,stat:监控统计、log4j:日志记录、wall:防御sql注入
        #如果允许时报错 java.lang.ClassNotFoundException: org.apache.log4j.Priority
        #则导入 log4j 依赖即可,Maven 地址:https://mvnrepository.com/artifact/log4j/log4j
        filters: stat,wall,log4j
        maxPoolPreparedStatementPerConnectionSize: 20
        useGlobalDataSourceStat: true
        connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
    
    • 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
    • 导入Log4j的依赖
    
    <dependency>
        <groupId>log4jgroupId>
        <artifactId>log4jartifactId>
        <version>1.2.17version>
    dependency>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 为DruidDataSource 绑定全局配置文件中的参数,再添加到容器中,而不再使用Spring Boot的自动生成了;需要自己添加DruidDataSource组件到容器中,并绑定属性;
    • 编写DruidConfig
    import java.util.HashMap;
    import java.util.Map;
    
    /**
     * @author BoBooY
     * @date 2022/9/17 17:19
     */
    @Configuration
    public class DruidConfig {
        /**
         * 将自定义的 Druid数据源添加到容器中,不再让 Spring Boot 自动创建
         * 绑定全局配置文件中的 druid 数据源属性到 com.alibaba.druid.pool.DruidDataSource从而让它们生效
         *
         * @ConfigurationProperties(prefix = "spring.datasource"):作用就是将 全局配置文件中
         * 前缀为 spring.datasource的属性值注入到 com.alibaba.druid.pool.DruidDataSource 的同名参数中
         */
        @ConfigurationProperties(prefix = "spring.datasource")
        @Bean
        public DataSource druidDataSource() {
            return new DruidDataSource();
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22

    2.3、配置 Druid 数据源监控

    • Druid 数据源具有监控的功能,并提供了一个web界面方便用户查看,类似安装路由器时,人家也提 供了一个默认的web页面。
    • 所以第一步需要设置 Druid 的后台管理页面,比如登录账号、密码等;配置后台管理;
    • 编写DruidConfig
    @Bean
    public ServletRegistrationBean statViewServlet() {
        ServletRegistrationBean bean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*");
        // 这些参数可以在 com.alibaba.druid.support.http.StatViewServlet的父类 com.alibaba.druid.support.http.ResourceServlet 中找到
        Map<String, String> initParams = new HashMap<>();
        initParams.put("loginUsername", "admin");
        initParams.put("loginPassword", "123456");
        // deny:Druid 后台拒绝谁访问
        // initParams.put("deny", "192.168.1.20");表示禁止此ip访问
    
        bean.setInitParameters(initParams);
        return bean;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 访问 http://localhost:8080/druid

    在这里插入图片描述

    2.4、配置 Druid web监控过滤器

    • 编写DruidConfig
    // 配置 Druid 监控 之  web 监控的 filter
    // WebStatFilter:用于配置Web和Druid数据源之间的管理关联监控统计
    @Bean
    public FilterRegistrationBean webStatFilter() {
        FilterRegistrationBean bean = new FilterRegistrationBean();
        bean.setFilter(new WebStatFilter());
        // exclusions:设置哪些请求进行过滤排除掉,从而不进行统计
        HashMap<String, String> initParams = new HashMap<>();
        initParams.put("exclusions","*.js,*.css,/druid/*,/jdbc/*");
        bean.setInitParameters(initParams);
        // "/*" 表示过滤所有请求
        bean.setUrlPatterns(Arrays.asList("/*"));
        return bean;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14

    3、整合 Mybatis 框架

    3.1、导入依赖

    <dependency>
        <groupId>org.mybatis.spring.bootgroupId>
        <artifactId>mybatis-spring-boot-starterartifactId>
        <version>2.2.2version>
    dependency>
    
    • 1
    • 2
    • 3
    • 4
    • 5

    3.2、配置数据库连接信息

    • application.yaml
    spring:
      datasource:
        username: root
        password: 1234
        url: jdbc:mysql://localhost:3306/mybatis?useSSL=true&useUnicode=true&characterEncoding=utf8
        driver-class-name: com.mysql.jdbc.Driver
        type: com.alibaba.druid.pool.DruidDataSource # 自定义数据源
    
        #数据源
        #Spring Boot 默认是不注入这些属性值的,需要自己绑定
        #druid 数据源专有配置
        initialSize: 5
        minIdle: 5
        maxActive: 20
        maxWait: 60000
        timeBetweenEvictionRunsMillis: 60000
        minEvictableIdleTimeMillis: 300000
        validationQuery: SELECT 1 FROM DUAL
        testWhileIdle: true
        testOnBorrow: false
        testOnReturn: false
        poolPreparedStatements: true
        #配置监控统计拦截的filters,stat:监控统计、log4j:日志记录、wall:防御sql注入
        #如果允许时报错 java.lang.ClassNotFoundException: org.apache.log4j.Priority
        #则导入 log4j 依赖即可,Maven 地址:https://mvnrepository.com/artifact/log4j/log4j
        filters: stat,wall,log4j
        maxPoolPreparedStatementPerConnectionSize: 20
        useGlobalDataSourceStat: true
        connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
    
    • 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

    3.3、编写实体类

    • User 类
    package com.springboot07mybatis.pojo;
    
    import lombok.AllArgsConstructor;
    import lombok.Data;
    import lombok.NoArgsConstructor;
    
    /**
     * @author BoBooY
     * @date 2022/9/17 21:07
     */
    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    public class User {
        private int id;
        private String name;
        private String pwd;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18

    3.4、编写mapper接口

    • UserMapper
    package com.springboot07mybatis.mapper;
    
    import com.springboot07mybatis.pojo.User;
    import org.apache.ibatis.annotations.Mapper;
    import org.springframework.stereotype.Repository;
    
    import java.util.List;
    
    /**
     * @author BoBooY
     * @date 2022/9/17 21:08
     */
    @Repository
    @Mapper
    public interface UserMapper {
    
        List<User> getUserList();
    
        User getUserById(int id);
    
        int addUser(User user);
    
        int updateUser(User user);
    
        int deleteUser(int 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

    3.5、编写mapper映射文件

    • UserMapper.xml
    
    DOCTYPE mapper
            PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
            "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    <mapper namespace="com.springboot07mybatis.mapper.UserMapper">
        
    
        <select id="getUserList" resultType="User">
            select * from user
        select>
    
        <select id="getUserById" resultType="User" parameterType="int">
            select * from user where id = #{id}
        select>
    
        <insert id="addUser" parameterType="User">
            insert into user(`name`,`pwd`) values(#{name},#{pwd})
        insert>
    
        <update id="updateUser" parameterType="User">
            update user set `name`=#{name},`pwd`=#{pwd} where `id`=#{id}
        update>
    
        <delete id="deleteUser" parameterType="int">
            delete from user where `id`=#{id}
        delete>
    mapper>
    
    • 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

    3.6、核心配置文件指定mapper映射文件

    • application.yaml
    #配置Mybatis
    mybatis:
      # 指定myBatis的核心配置文件与Mapper映射文件
      mapper-locations: classpath:mybatis/mapper/*.xml
      # 注意:对应实体类的路径
      type-aliases-package: com.springboot07mybatis.pojo
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    3.7、解决 maven 资源过滤问题

    • pom.xml
    <build>
        <resources>
            <resource>
                <directory>src/main/javadirectory>
                <includes>
                    <include>**/*.propertiesinclude>
                    <include>**/*.xmlinclude>
                    <include>**/*.ymlinclude>
                    <include>**/*.yamlinclude>
                includes>
                <filtering>falsefiltering>
            resource>
            <resource>
                <directory>src/main/resourcesdirectory>
                <includes>
                    <include>**/*.propertiesinclude>
                    <include>**/*.xmlinclude>
                    <include>**/*.ymlinclude>
                    <include>**/*.yamlinclude>
                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
    • 22
    • 23
    • 24

    3.8、编写Controller测试

    • UserController
    package com.springboot07mybatis.controller;
    
    import com.springboot07mybatis.mapper.UserMapper;
    import com.springboot07mybatis.pojo.User;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.PathVariable;
    import org.springframework.web.bind.annotation.RestController;
    
    import java.util.List;
    
    /**
     * @author BoBooY
     * @date 2022/9/17 21:25
     */
    @RestController
    public class UserController {
    
        @Autowired
        UserMapper userMapper;
    
        @GetMapping("/getUsers")
        public List<User> getUsers() {
            List<User> users = userMapper.getUserList();
            for (User user : users) {
                System.out.println(user);
            }
            return users;
        }
        @GetMapping("/getUser/{id}")
        public User getUser(@PathVariable("id") int id) {
            User user = userMapper.getUserById(id);
            return user;
        }
    
        @GetMapping("/updateUser")
        public String updateUser() {
            User user = getUser(4);
            user.setName("laosi");
            user.setPwd("1234");
            int i = userMapper.updateUser(user);
            if(i > 0) {
                return "修改成功";
            } else {
                return "修改失败";
            }
        }
    
        @GetMapping("/addUser")
        public String addUser() {
            User user = new User();
            user.setName("老五");
            user.setPwd("123");
            int i = userMapper.addUser(user);
            if(i > 0) {
                return "添加成功";
            } else {
                return "添加失败";
            }
        }
        @GetMapping("/deleteUser/{id}")
        public String deleteUser(@PathVariable("id") int id) {
            int i = userMapper.deleteUser(id);
            if(i > 0) {
                return "删除成功";
            } else {
                return "删除失败";
            }
        }
    }
    
    • 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
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 测试,功能正常,ok!
  • 相关阅读:
    Win10 系统中用户环境变量和系统环境变量是什么作用和区别?
    国际阿里云服务器到期多久会释放资源信息?
    如何使用前端框架(React、Angular、Vue.js等)?该如何选择?
    (8)Lightweight OpenPose轻量化模型之 模型封装 + 摔倒检测
    使用dockerfile部署springboot应用
    电脑硬盘就一个c盘怎么分区,新电脑买回来只有一个c盘怎么分区
    OpenCV实现物体尺寸的测量
    source activate my_env 和conda activate my_env 有什么区别
    Java 性能优化实战案例分析:并行计算让代码“飞”起来
    程序开发常用在线工具汇总
  • 原文地址:https://blog.csdn.net/qq_58233406/article/details/126914820