SpringBoot与数据访问(JDBC)

一、整合最基本的JDBC

1.引入最基本的jdbc和MySQL驱动依赖
<dependency>                         //jdbc依赖
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>

<dependency>                         //引入MySQL驱动
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.48</version>
        <!--<scope>runtime</scope>-->
</dependency>
2.访问数据库时必不可少的配置(在此采用yml文件)
spring:
    datasource:
        username: root
        password: 1234567890
        url: jdbc:mysql://localhost:3306/jdbc?useUnicode=true&characterEncoding=utf8
        driver-class-name: com.mysql.jdbc.Driver    
        initialization-mode: always            #初始化模式其中有三个值,always为始终执行初始化,embedded只初始化内存数据库(默认值),如h2等,never为不执行初始化。
1.SpringBoot2.0及以上必须加上初始化模式

==1)、驱动类使用com.mysql.jdbc.Driver时必须将依赖文件中的mysql-connector-java版本升至5.x以上
==2)、com.mysql.jdbc.Driver 是 mysql-connector-java 5中的,com.mysql.cj.jdbc.Driver 是 mysql-connector-java 6中的==

2.SpringBoot2.0以上默认的数据源是:class com.zaxxer.hikari.Hikar.iDataSource
3.数据源的相关配置都在DataSourceProperties类里面

自动配置原理都在:org.springframework.boot.autoconfigure.jdbc

1).参考DataSourceConfiguration根据配置创建数据源,默认使用hikari连接池;可以使用spring.datasource.type指定自定义的数据源类型
2).SpringBoot默认支持
com.zaxxer.hikari.HikariDataSource
org.apache.commons.dbcp2.BasicDataSource
org.apache.tomcat.jdbc.pool.DataSource
3).自定义数据源类型
@Configuration(
        proxyBeanMethods = false
    )
    @ConditionalOnMissingBean({DataSource.class})
    @ConditionalOnProperty(
        name = {"spring.datasource.type"}
    )
    static class Generic {
        Generic() {
        }
        @Bean
        DataSource dataSource(DataSourceProperties properties) {
        //使用DataSourceBuilder创建数据源,利用反射创建相应type的数据源,并且绑定相关的属性
            return properties.initializeDataSourceBuilder().build();
        }
    }
4).DataSourceInitializer是ApplicationListener类型的监听器

spring.datasource下有两个属性 schme、data,其中schema为表初始化语句(建表)data为数据初始化(数据),默认加载schema.sql与data.sql。脚本位置可以通过spring.datasource.schema 与spring.datasource.data 来改变,源码如下:

boolean createSchema() {
        List<Resource> scripts = this.getScripts("spring.datasource.schema", this.properties.getSchema(), "schema");
        if (!scripts.isEmpty()) {
            if (!this.isEnabled()) {
                logger.debug("Initialization disabled (not running DDL scripts)");
                return false;
            }
            String username = this.properties.getSchemaUsername();
            String password = this.properties.getSchemaPassword();
            this.runScripts(scripts, username, password);
        }
        return !scripts.isEmpty();
    }

    void initSchema() {
        List<Resource> scripts = this.getScripts("spring.datasource.data", this.properties.getData(), "data");
        if (!scripts.isEmpty()) {
            if (!this.isEnabled()) {
                logger.debug("Initialization disabled (not running data scripts)");
                return;
            }
            String username = this.properties.getDataUsername();
            String password = this.properties.getDataPassword();
            this.runScripts(scripts, username, password);
        }
    }

作用:
1)、createSchema,initSchema 创建,初始化并且运行建表语句对应2.0以下版本的runSchemaScripts
2)、getScripts 运行插入数据的语句 对应2.0以下版本的runDataScripts
默认只需将文件命名为:

schema-*.sql、data-*.sql
默认规则:schema.sql,schema-all.sql;

如果运行自定义sql文件则指定sql文件的位置

initialization-mode: always
schema:
    - classpath:department.sql           #指定sql文件的位置

initialization-mode: always需要生命脚本总是启动(在配置文件中加上这个配置信息,如果不加sql文件不会执行会使页面出现404错误

5).操作数据库:自动配置了JdbcTemplate操作数据库;

编写一个Controller测试JdbcTemplate

package com.atorg.springboot.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.ResponseBody;
import java.util.List;
import java.util.Map;
@Controller
public class HelloController {

    @Autowired    //注入jdbctemplate
    JdbcTemplate jdbcTemplate;

    @ResponseBody          //把数据写到web页面
    @GetMapping("/query")     //发送query请求
    public Map<String,Object> map(){
        List<Map<String, Object>> list = jdbcTemplate.queryForList("select * FROM department");
        return list.get(0);          //查询第一条数据
    }
}

注意运行一次程序就会新建一次sql数据表,运行完就将sql文件删除即可
运行创建数据库jdbc
运行截图
运行截图

二、整合数据源Druid

1)、配置信息
spring:
    datasource:
        username: root
        password: 1234567890
        url: jdbc:mysql://localhost:3306/jdbc?useUnicode=true&characterEncoding=utf8
        driver-class-name: com.mysql.jdbc.Driver
        initialization-mode: always

    ##################################################################
    type: com.alibaba.druid.pool.DruidDataSource
    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,去掉后监控界面sql无法统计,'wall'用于防火墙
    filters: stat,wall,slf4j
    maxPoolPreparedStatementPerConnectionSize: 20
    useGlobalDataSourceStat: true
    connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500

      #      schema:
      #        - classpath:department.sql

#######以下的属性并不能绑定到数据库的配置里面,启动程序以后这些配置使不起作用的,如果要想这些配置信息起作用必须写一个配置类将这些配置信息的路径写明

    //导入druid数据源
    @ConfigurationProperties(prefix ="spring.datasource")    //表明配置文件起作用的是从spring.datasource开始的所有都起作用
        @Bean
        public DataSource druid(){
            return new DruidDataSource();
        }
2)、配置druid监控
    //配置druid监控
        //1.配置管理后台的servlet
        @Bean
        public ServletRegistrationBean statViewServlet(){
            ServletRegistrationBean bean=new ServletRegistrationBean(new StatViewServlet(),"/druid/*");
            Map<String,String> initParams =new HashMap<>();
            initParams.put("loginUsername","admin");//配置druid登陆名
            initParams.put("loginPassword","123456");//配置druid登陆密码
            initParams.put("allow", "");//默认允许所有
            initParams.put("deny", "192.168.43.177");//拒绝此用户访问
            bean.setInitParameters(initParams);//配置初始化参数
            return bean;
        }
        //2.配置一个监控的filter
        @Bean
        public FilterRegistrationBean webStatFilter(){
            FilterRegistrationBean bean = new FilterRegistrationBean();
            bean.setFilter(new WebStatFilter());
            Map<String,String> initParams=new HashMap<>();
            initParams.put("exclusions", "*.js,*.css,/druid/*");//拦截的所有请求中排除*.js,*.css,/druid/*请求
            bean.setInitParameters(initParams);//初始化参数
            bean.setUrlPatterns(Arrays.asList("/*"));//拦截所有请求
            return bean;
        }

http://localhost:8080/druid/
登录名为:admin 登陆密码:123456


Author: Lelege
Reprint policy: All articles in this blog are used except for special statements CC BY 4.0 reprint polocy. If reproduced, please indicate source Lelege !
评论
 Previous
SpringBoot与数据访问(JPA) SpringBoot与数据访问(JPA)
四、整合SpringData JPA操作数据库1.引入JPA依赖JPA:ORM(Object Relational Mapping) <dependency> <groupId>org.s
Next 
MySQL数据库基础(中-1) MySQL数据库基础(中-1)
MySQL数据库基本操作2 使用聚合函数查询2.4 COUNT()函数(实例)COUNT()函数用来统计记录的条数;与 GOUPE BY 关键字一起使用SELECT COUNT(*) FROM t_grade;//用来统计记录的条数 SEL
2019-12-28
  TOC