springboot 整合JDBC、Druid

1、SpringData简介

(1)在springboot框架中,数据访问层,无论是SQL还是NOSQL ,springBoot底层使用的是springdata的方式处理的

(2) SpringData 官网:Spring Data

2、Springboot 整合JDBC

2.1创建测试数据

使用步骤:

​ 1.创建一个springboot项目(springboot-data-jdbc)

​ 1.1.1 创建项目的时候导入了

     <!--springboot 整合JDBC-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <!--web项目启动器-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

​ 1.1.2 添加数据连接依赖

 <!--数据库连接 -->
        <!--springboot 2.5.0 规定了mysql版本:<mysql.version>8.0.25</mysql.version> -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>

2.写yml文件,配置数据库连接

server:
  port: 8080
  servlet:
    context-path:
spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url:  jdbc:mysql://localhost:3306/springboot?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
    username: root
    password: ****

3.测试类测试,是和否连接成功(springboot默认自动配置)

@SpringBootTest
class JdbcApplicationTests {
    //测试连接
    @Autowired
    private DataSource dataSource;

    @Test
    void contextLoads() throws SQLException {
        //查看数据源
        System.out.println("数据源名称:"+dataSource.getClass());
        //获取连接诶
        Connection connection = dataSource.getConnection();
        System.out.println("连接对象:"+connection);
        //关闭连接
        connection.close();

    }
}

​ 4.测试结果:
在这里插入图片描述

默认配置的数据源是:class com.zaxxer.hikari.HikariDataSource

全局搜索(ctrl+shift+F):找到数据源自动配置类
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

在配置类下发现:springboot2.2.5默认使用HikarPoolDataSource数据源,在springboot1.5默认使用org.apache.tomcat.jdbc.pool.DataSource作为数据源。
可使用spring.datasource.type自动以数据源类型,使用连接池的完全限定名。

HikarDatasource 是javaweb 速度就快的数据源,相比于传统的c3p0、dbcp、Tomcat jdbc

2.2 JDBCTemplate

2.2.1介绍

​ 1.有数据源(HikariDataSource),就能拿到数据连接对象(Connection),有了连接对象,就可以使用原生的JDBC语句来操作数据库。

​ 2.不使用第三方的数据库框架(Mybatis),spring本身就对原生的jdbc做了轻量级的封装(JDBCTemplate)---->(CRUD)

​ 3.springboot 默认提供了数据源,同时把已经把jdbctemplate放在了容器中

​ 4.JDBC Template的自动配置依赖的是 org.springframework.boot.autoConfigure.jdbc包下的JdbcTemplateConfiguration类

JdbcTemplate主要提供以下几类方法:

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

​ 代码测试:

@RestController
public class JDBCTemplateController {
    /**
     * spring自配配置数据源,也会自动装入
     */
    @Resource
    private JdbcTemplate jdbcTemplate;

    /**
     * 查询数据库的数据
     * List表示一条数据
     * Map<字段名 ,属性值>
     *
     * @return
     */
    @GetMapping("/list")
    public List<Map<String, Object>> userList() {
        String sql = "select * from user";
        List<Map<String, Object>> maps = jdbcTemplate.queryForList(sql);
        return maps;
    }

    /**
     * 修改数据的
     */
    @GetMapping("/update/{id}")
    public Integer updateUser(@PathVariable("id") int id) {
        String sql = "update user set username=? where id=" + id;
        //创建数据对象
        Object[] o = new Object[1];
        o[0] = "JJ";
        int i = jdbcTemplate.update(sql, o);
        return i;
    }

    /**
     * 添加数据
     */
    @GetMapping("/add")
    public Integer addUser() {
        String sql = "insert into user(username,password) values('Austin','Austin')";
        int i = jdbcTemplate.update(sql);
        return i;

    }

    /**
     * 删除数据
     */
    @GetMapping("delete/{id}")
    public Integer deleterUser(@PathVariable("id") int id) {
        String sql = "delete from user where id=" + id;
        int i = jdbcTemplate.update(sql);
        return i;
    }


}

3、集成Druid

3.1Druid简介

3.2使用步骤

​ 3.2.1配置数据源

​ 1、添加Druid的依赖

<!--Druid-->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId>
    <version>1.2.3</version>
</dependency>
<!--springboot整合druid-->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid-spring-boot-starter</artifactId>
    <version>1.2.3</version>
</dependency>
<!--配置监控统计拦截的filters,stat:监控统计、log4j:日志记录、wall:防御sql注入-->
<dependency>
    <groupId>log4j</groupId>
    <artifactId>log4j</artifactId>
    <version>1.2.17</version>
</dependency>

​ 2、切换数据源

springboot 2.0以上默认使用HikarDataDSource数据源,但是可以通过 spring.datasource.type指定数据源。
spring:
  datasource:
    username: root
    password: root
    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

​ 3、测试类中测试

在这里插入图片描述

​ 4、 测试成功后,设置数据源初始化的大小、最大的连接数、等待时间、最小连接数等等

spring:
  datasource:
    username: root
    password: root
    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

    # 下面为连接池的补充设置,应用到上面所有数据源中
    # 初始化大小,最小,最大
    druid:
      initial-size: 5
      min-idle: 5
      max-active: 20
      # 配置获取连接等待超时的时间
      max-wait: 60000
      # 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
      time-between-eviction-runs-millis: 60000
      # 配置一个连接在池中最小生存的时间,单位是毫秒
      min-evictable-idle-time-millis: 300000
      validation-query: SELECT 1 FROM DUAL
      test-while-idle: true
      test-on-borrow: false
      test-on-return: false
      # 打开PSCache,并且指定每个连接上PSCache的大小
      pool-prepared-statements: true
      max-pool-prepared-statement-per-connection-size: 20
      # 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙,此处是filter修改的地方
      filter:
        commons-log:
          connection-logger-name: stat,wall,log4j
      # 通过connectProperties属性来打开mergeSql功能;慢SQL记录
      connect-properties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
      # 合并多个DruidDataSource的监控数据
      use-global-data-source-stat: true

​ 5、导入log4j依赖

<!--配置监控统计拦截的filters,stat:监控统计、log4j:日志记录、wall:防御sql注入-->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>

​ 6、为DruiDDataSource绑定全局文件参数,添加到容器中(因为使用springboot不再自动生成的,需要自己添加DruidDataSource组件中),绑定属性。

@Configuration
public class DruidDataSourceConfig {
    /**
     * 将自定义Druid数据源添加到容器中(springboot不会自动配置)
     *   @ConfigurationProperties(prefix = "spring.datasource"):
     *   作用就是将 全局配置文件中
     *        前缀为 spring.datasource的属性值注入到 com.alibaba.druid.pool.DruidDataSource 的同名参数中
     */

    @ConfigurationProperties(prefix = "spring.datasource.druid")
    @Bean
    public DataSource druidDataSource(){
        return new DruidDataSource();
    }
}

​ 7、测试类型中测试

@SpringBootTest
class JdbcApplicationTests {
    //测试连接
    @Autowired
    private DataSource dataSource;
    @Test
    void contextLoads() throws SQLException {
        //查看数据源
        System.out.println("数据源名称:" + dataSource.getClass());
        DruidDataSource druidDataSource = (DruidDataSource) dataSource;
        System.out.println("druidDataSource 数据源最大连接数:" + druidDataSource.getMaxActive());
        System.out.println("druidDataSource 数据源初始化连接数:" + druidDataSource.getInitialSize());
    }
}

在这里插入图片描述

​ 3.2.2 配置Druid数据源监控

Druid数据源具有监控的功能,并提供了一个web界面方面用户查看,(类似路由)

​ 在Druid的配置文件中配置数据源的监控

/**
     * 配置Druid 监控管理后台的Servlet
     * 内置 Servlet 容器中没有web.xml,所以使用springboot注册servlet
     *
     */
    @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", "Austin"); //后台管理界面的登录账号
        initParams.put("loginPassword", "XX"); //后台管理界面的登录密码

        //后台允许谁可以访问
        //initParams.put("allow", "localhost"):表示只有本机可以访问
        //initParams.put("allow", ""):为空或者为null时,表示允许所有访问
        initParams.put("allow", "");
        //deny:Druid 后台拒绝谁访问
        //initParams.put("Austin", "192.168.1.11");表示禁止此ip访问

        //设置初始化参数
        bean.setInitParameters(initParams);
        return bean;
    }

​ 1、设置Druid的后台管理页面,登录账号、密码; 配置后台管理
在这里插入图片描述

​ 2、访问测试:http://localhost:8080/druid/login.html

​ 3、界面
在这里插入图片描述

​ 4、配置Druid Web监控filter过滤器(作用:监控)

 /**
     *  配置 Druid 监控 之  web 监控的 filter
     *  WebStatFilter:用于配置Web和Druid数据源之间的管理关联监控统计
     */
    @Bean
    public FilterRegistrationBean webStatFilter() {
        FilterRegistrationBean bean = new FilterRegistrationBean();
        bean.setFilter(new WebStatFilter());

        //exclusions:设置哪些请求进行过滤排除掉,从而不进行统计
        Map<String, String> initParams = new HashMap<>();
        initParams.put("exclusions", "*.js,*.css,/druid/*,/jdbc/*");
        bean.setInitParameters(initParams);

        //"/*" 表示过滤所有请求
        bean.setUrlPatterns(Arrays.asList("/*"));
        return bean;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值