尚硅谷学习笔记---SpringBoot与数据访问

简介

  • 对于数据访问层,无论是SQL还是NOSQL,Spring Boot默认采用整合
    Spring Data的方式进行统一处理,添加大量自动配置,屏蔽了很多设置。引入
    各种xxxTemplate,xxxRepository来简化我们对数据访问层的操作。对我们来
    说只需要进行简单的设置即可。我们将在数据访问章节测试使用SQL相关、
    NOSQL在缓存、消息、检索等章节测试。
    – JDBC
    – MyBatis
    – JPA

jdbc与自动配置原理

  • 要在SpringBoot应用中使用原生的JDBC只需要在pom文件中加入以下依赖
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
	<groupId>mysql</groupId>
	<artifactId>mysql-connector-java</artifactId>
	<scope>runtime</scope>
</dependency>
  • 或者直接使用IDEA新建项目时选中JDBC

在这里插入图片描述

  • 编写SpringBoot配置文件
spring:
  datasource:
    username: root
    password: 123456
    url: jdbc:mysql://localhost:3306/springboottest
    driver-class-name: com.mysql.jdbc.Driver
    
  • 在测试类中,测试获取数据源对象

@Autowired
private DataSource dataSource;

@Test
public void contextLoads() throws SQLException {
   System.out.println("================================>"+dataSource);

   Connection connection = dataSource.getConnection();
   System.out.println("================================>"+connection);
}

在这里插入图片描述

在这里插入图片描述

效果:

​ 默认是用org.apache.tomcat.jdbc.pool.DataSource作为数据源;

​ 数据源的相关配置都在DataSourceProperties里面;

自动配置原理:

org.springframework.boot.autoconfigure.jdbc:

1、参考DataSourceConfiguration,根据配置创建数据源,默认使用Tomcat连接池;可以使用spring.datasource.type指定自定义的数据源类型;

2、SpringBoot默认可以支持;

org.apache.tomcat.jdbc.pool.DataSource、HikariDataSource、BasicDataSource、

3、自定义数据源类型

/**
 * Generic DataSource configuration.
 */
@ConditionalOnMissingBean(DataSource.class)
@ConditionalOnProperty(name = "spring.datasource.type")
static class Generic {

   @Bean
   public DataSource dataSource(DataSourceProperties properties) {
       //使用DataSourceBuilder创建数据源,利用反射创建响应type的数据源,并且绑定相关属性
      return properties.initializeDataSourceBuilder().build();
   }

}

4、DataSourceInitializer:ApplicationListener

​ 作用:

​ 1)、runSchemaScripts();运行建表语句;

​ 2)、runDataScripts();运行插入数据的sql语句;

默认只需要将文件命名为:

schema-*.sql、data-*.sql
默认规则:schema.sql,schema-all.sql;
可以使用   
	schema:
      - classpath:department.sql
      指定位置

5、操作数据库:自动配置了JdbcTemplate操作数据库

整合Druid&配置数据源监控

  1. 导入Druid依赖
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId>
    <version>1.1.17</version>
</dependency>

  • 修改SpringBoot配置文件,将数据连接源类型改为:" type: com.alibaba.druid.pool.DruidDataSource"
spring:
  datasource:
    username: root
    password: 123456
    url: jdbc:mysql://localhost:3306/springboottest
    driver-class-name: com.mysql.jdbc.Driver
    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,log4j
    maxPoolPreparedStatementPerConnectionSize: 20
    useGlobalDataSourceStat: true
    connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500

  • 并且要使数据源链接初始配置起作用,需要另外编写配置类来指定配置项
  • 编写MyDruidConf

@Configuration
public class MyDruidConf {


    @ConfigurationProperties(prefix = "spring.datasource")//制定配置项开头
    @Bean
    public DataSource druid() {
        return new DruidDataSource();
    }
}

  • 配置Druid的监控
  //1、配置一个管理后台的Servlet
    @Bean
    public ServletRegistrationBean statViewServlet(){
        ServletRegistrationBean bean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*");
        Map<String,String> initParams = new HashMap<>();

        initParams.put("loginUsername","admin");
        initParams.put("loginPassword","123456");
        initParams.put("allow","");//默认就是允许所有访问
        initParams.put("deny","192.168.15.21");

        bean.setInitParameters(initParams);
        return bean;
    }


    //2、配置一个web监控的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/*");

        bean.setInitParameters(initParams);

        bean.setUrlPatterns(Arrays.asList("/*"));

        return  bean;
    }

在这里插入图片描述

在这里插入图片描述

整合MyBatis

  • 准备环境,创建项目,pom文件内容
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.9.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>mao.shu</groupId>
    <artifactId>springbootmybatis</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>springbootmybatis</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.1.1</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.17</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

  • 配置数据源
  • application.yml文件
spring:
  datasource:
    username: root
    password: 123456
    url: jdbc:mysql://localhost:3306/springboottest
    driver-class-name: com.mysql.jdbc.Driver
    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,log4j
    maxPoolPreparedStatementPerConnectionSize: 20
    useGlobalDataSourceStat: true
    connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500


  • 创建数据表
CREATE TABLE `department` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `departmentName` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE `employee` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `lastName` varchar(255) DEFAULT NULL,
  `email` varchar(255) DEFAULT NULL,
  `gender` int(2) DEFAULT NULL,
  `d_id` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
  • 创建对应的实体类

MyBatis注解版

  • 创建Mapper接口
package mao.shu.springbootmybatis.dao;

import mao.shu.springbootmybatis.entity.Department;
import org.apache.ibatis.annotations.*;

@Mapper
public interface DepartmentDao {

    @Select("select id,departmentName from department where id=#{id}")
    public Department selectById(Integer id);


    @Delete("delete from department where id=#{id}")
    public int deleteById(Integer id);

    @Options(useGeneratedKeys = true, keyProperty = "id")//指定自动增长列
    @Insert("insert into department(departmentName) values(#{departmentName}) ")
    public int insert(Department department);


    @Update("update department set departmentName=#{departmentName} where id=#{id}")
    public int update(Department department);

}

  • 当需要为MyBatis进行配置的时候,给容器中添加一个ConfigurationCustomizer;
  • 只有当MyBatis适配包版本为1.3.1以上才能够正确使用ConfigurationCustomizer类
package mao.shu.springbootmybatis.config;

import org.mybatis.spring.boot.autoconfigure.ConfigurationCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class MyBatisConfig {

    @Bean
    public ConfigurationCustomizer configurationCustomizer() {
        return new ConfigurationCustomizer() {
            @Override
            public void customize(org.apache.ibatis.session.Configuration configuration) {
            //设置驼峰命名法
                configuration.setMapUnderscoreToCamelCase(true);
            }
        };
    }
}

配置版MyBatis

  • 定义MyBatis全局配置文件
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <settings>
        <!--开启驼峰命名法-->
        <setting name="mapUnderscoreToCamelCase" value="true"/>
    </settings>
</configuration>
  • 定义sql语句映射文件
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="mao.shu.springbootmybatis.dao.EmployeeDao">

    <!--
        public Employee select(Integer id);

    public int insert(Employee employee);
    -->

    <select id="select" resultType="mao.shu.springbootmybatis.entity.Employee">
        select * from employee where id=#{id};
    </select>

    <insert id="insert">
        insert into employee(lastName,email,gender,dId) values (#{lastName},#{email},#{gender},#{gender},#{dId});
    </insert>
</mapper>
  • 编写SpringBoot配置文件,设置MyBatis配置文件和mapper文件位置
mybatis:
#设置MyBatis总配置文件位置
  config-location: classpath:mybatis/mybatis-config.xml
#  指定sql文件映射位置
  mapper-locations: classpath:mybatis/mapper/*.xml
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值