EmmmuaCode EmmmuaCode
首页​
导航🚀​
  • 数据结构
  • 计算机网络
  • Java基础

    • JavaSE
    • JVM虚拟机
    • JUC并发编程
  • JavaWeb

    • Servlet
    • MVC
    • filter|listener
  • HTML
  • CSS
  • JavaScript
  • Vue
  • uni-app
  • Spring5
  • SpringMVC
  • SpringBoot2
  • SpringCloud
  • SpringSecurity
  • 搜索引擎

    • ElasticSearch
  • 消息队列

    • RabbitMQ
  • 服务器

    • Nginx🌐
  • 服务框架

    • Dubbo
  • Python基础
  • 数据分析
  • Hadoop
  • SQL 数据库

    • MySQL
  • NoSQL 数据库

    • NoSQL数据库概论
    • Redis
    • MongoDB
    • HBase
  • 框架

    • MyBatis
    • MyBatis-Plus
    • ShardingSphere
  • 部署

    • Linux
    • Docker
  • 管理

    • Maven
    • Git
  • 友情链接
  • 优秀博客文章
  • 索引

    • 分类
    • 标签
    • 归档
  • 其他

    • 关于
Github (opens new window)

wufan

海内存知己,天涯若比邻。
首页​
导航🚀​
  • 数据结构
  • 计算机网络
  • Java基础

    • JavaSE
    • JVM虚拟机
    • JUC并发编程
  • JavaWeb

    • Servlet
    • MVC
    • filter|listener
  • HTML
  • CSS
  • JavaScript
  • Vue
  • uni-app
  • Spring5
  • SpringMVC
  • SpringBoot2
  • SpringCloud
  • SpringSecurity
  • 搜索引擎

    • ElasticSearch
  • 消息队列

    • RabbitMQ
  • 服务器

    • Nginx🌐
  • 服务框架

    • Dubbo
  • Python基础
  • 数据分析
  • Hadoop
  • SQL 数据库

    • MySQL
  • NoSQL 数据库

    • NoSQL数据库概论
    • Redis
    • MongoDB
    • HBase
  • 框架

    • MyBatis
    • MyBatis-Plus
    • ShardingSphere
  • 部署

    • Linux
    • Docker
  • 管理

    • Maven
    • Git
  • 友情链接
  • 优秀博客文章
  • 索引

    • 分类
    • 标签
    • 归档
  • 其他

    • 关于
Github (opens new window)
  • Spring5-基础

    • Spring5 入门案例
    • Spring核心之控制反转IOC
    • Spring核心之面向切面编程AOP
    • Jdbc Template
    • Spring5 事务
    • Spring5 新功能
    • Spring5 Webflux
  • SpringMVC-基础

    • SpringMVC 入门案例
    • RequestMapping注解
    • SpringMVC 获取请求参数
    • 域对象共享数据
    • SpringMVC的视图
    • RESTFul
    • RESTful案例
    • HttpMessageConverter
    • 文件上传和下载
    • 拦截器
    • 异常处理器
    • 注解配置SpringMVC
    • SpringMVC执行流程
  • SpringBoot2-基础

    • Spring与SpringBoot
    • SpringBoot2 快速入门
    • SpringBoot2 常用注解
    • 了解自动装配原理
  • SpringBoot2-核心功能

    • 配置文件
    • Web开发
    • 数据访问
      • SQL
        • 数据源的自动配置-HikariDataSource
        • 导入JDBC场景
        • 分析自动配置
        • 修改配置项
        • 测试
      • 使用Druid数据源
        • druid官方github地址
        • 自定义方式
        • 创建数据源
        • StatViewServlet
        • StatFilter
        • 使用官方starter方式
        • 引入druid-starter
        • 分析自动配置
        • 配置示例
      • 整合MyBatis操作
        • 配置模式
        • 注解模式
        • 混合模式
    • 单元测试
  • SpringCloud-微服务架构

    • 微服务架构理论入门
    • SpringCloud 初步构建
    • Eureka 服务注册与发现
    • ZooKeeper 服务注册与发现
    • Consul 服务注册与发现
    • Ribbon 负载均衡服务调用
    • OpenFeign 简化服务调用
    • Hystrix 服务降级|熔断
    • GateWay 服务网关
    • Config 服务配置中心 与 BUS 消息总线
    • Stream 消息驱动
    • Sleuth 分布式请求链路追踪
  • SpringCloud Alibaba

    • SpringCloud Alibaba 简介
    • Nacos 服务发现、配置管理和服务管理平台
    • Sentinel 实现熔断与限流
    • Seata 分布式事务
  • Spring Security

    • SpringSecurity 概述
    • SpringSecurity 入门案例
    • SpringSecurity 登录认证详解
    • SpringSecurity 授权
    • SpringSecurity 跨域
    • SpringSecurity 遗留小问题
  • studynotes
  • Spring
  • SpringBoot2
wufan
2022-04-08
目录

数据访问

# 数据访问

# SQL

# 数据源的自动配置-HikariDataSource

# 导入JDBC场景

   <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jdbc</artifactId>
        </dependency>
1
2
3
4

01

数据库驱动?

为什么导入JDBC场景,官方不导入驱动?官方不知道我们接下要操作什么数据库。

数据库版本和驱动版本对应

<!-- 默认版本:<mysql.version>8.0.22</mysql.version> -->

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
<!--            <version>5.1.49</version>-->
        </dependency>
1
2
3
4
5
6
7

想要修改版本

  1. 直接依赖引入具体版本(maven的就近依赖原则)
  2. 重新声明版本(maven的属性的就近优先原则)
 	<properties>
        <java.version>1.8</java.version>
        <mysql.version>5.1.49</mysql.version>
    </properties>
1
2
3
4

# 分析自动配置

自动配置的类

  • DataSourceAutoConfiguration:数据源的自动配置
    • 修改数据源相关的配置:spring.datasource
    • 数据库连接池的配置,是自己容器中没有DataSource才自动配置
    • 底层配置好的连接池是:HikariDataSource
	@Configuration(proxyBeanMethods = false)
	@Conditional(PooledDataSourceCondition.class)
	@ConditionalOnMissingBean({ DataSource.class, XADataSource.class })
	@Import({ DataSourceConfiguration.Hikari.class, DataSourceConfiguration.Tomcat.class,
			DataSourceConfiguration.Dbcp2.class, DataSourceConfiguration.OracleUcp.class,
			DataSourceConfiguration.Generic.class, DataSourceJmxConfiguration.class })
	protected static class PooledDataSourceConfiguration
1
2
3
4
5
6
7
  • DataSourceTransactionManagerAutoConfiguration: 事务管理器的自动配置
  • jdbcTemplateAutoConfiguration: JdbcTemplate的自动配置,可以来对数据库进行crud
    • 可以修改这个配置项@ConfigurationProperties(prefix = "spring.jdbc")来修改JdbcTemplate
    • @Bean@Primary JdbcTemplate;容器中有这个组件
  • JndiDataSourceAutoConfiguration: jndi的自动配置
  • XADataSourceAutoConfiguration: 分布式事务相关的

# 修改配置项

spring:
  datasource:
    url: jdbc:mysql://localhost:3306/maven
    username: root
    password: hsp
    driver-class-name: com.mysql.jdbc.Driver
1
2
3
4
5
6

# 测试

@Slf4j
@SpringBootTest
class Boot05WebAdminApplicationTests {

    @Autowired
    JdbcTemplate jdbcTemplate;

    @Test
    void contextLoads() {

        Long aLong = jdbcTemplate.queryForObject("select count(*) from user", Long.class);
        log.info("记录总数:{}",aLong);
    }

}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
  • 输出
...
2022-04-09 18:07:11.268  INFO 11752 --- [           main] c.f.a.Boot05WebAdminApplicationTests     : 记录总数:1
2022-04-09 18:07:11.289  INFO 11752 --- [extShutdownHook] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Shutdown initiated...
2022-04-09 18:07:11.353  INFO 11752 --- [extShutdownHook] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Shutdown completed.
2022-04-09 18:07:11.354  INFO 11752 --- [extShutdownHook] o.s.s.concurrent.ThreadPoolTaskExecutor  : Shutting down ExecutorService 'applicationTaskExecutor'

Process finished with exit code 0
1
2
3
4
5
6
7

# 使用Druid数据源

# druid官方github地址

https://github.com/alibaba/druid

整合第三方技术的两种方式

  • 自定义
  • 找starter

# 自定义方式

# 创建数据源

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.16</version>
        </dependency>
1
2
3
4
5

# StatViewServlet

StatViewServlet的用途包括:

  • 提供监控信息展示的html页面
  • 提供监控信息的JSON API
	<servlet>
		<servlet-name>DruidStatView</servlet-name>
		<servlet-class>com.alibaba.druid.support.http.StatViewServlet</servlet-class>
	</servlet>
	<servlet-mapping>
		<servlet-name>DruidStatView</servlet-name>
		<url-pattern>/druid/*</url-pattern>
	</servlet-mapping>
1
2
3
4
5
6
7
8

# StatFilter

用于统计监控信息;如SQL监控、URI监控

需要给数据源中配置如下属性;可以允许多个filter,多个用,分割;如:

<property name="filters" value="stat,slf4j" />
1
2
3

系统中所有filter:

别名 Filter类名
default com.alibaba.druid.filter.stat.StatFilter
stat com.alibaba.druid.filter.stat.StatFilter
mergeStat com.alibaba.druid.filter.stat.MergeStatFilter
encoding com.alibaba.druid.filter.encoding.EncodingConvertFilter
log4j com.alibaba.druid.filter.logging.Log4jFilter
log4j2 com.alibaba.druid.filter.logging.Log4j2Filter
slf4j com.alibaba.druid.filter.logging.Slf4jLogFilter
commonlogging com.alibaba.druid.filter.logging.CommonsLogFilter

慢SQL记录配置

<bean id="stat-filter" class="com.alibaba.druid.filter.stat.StatFilter">
    <property name="slowSqlMillis" value="10000" />
    <property name="logSlowSql" value="true" />
</bean>

使用 slowSqlMillis 定义慢SQL的时长
1
2
3
4
5
6

# 使用官方starter方式

# 引入druid-starter

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.1.17</version>
        </dependency>
1
2
3
4
5

# 分析自动配置

  • 扩展配置项 spring.datasource.druid
  • DruidSpringAopConfiguration.class, 监控SpringBean的;配置项:spring.datasource.druid.aop-patterns
  • DruidStatViewServletConfiguration.class, 监控页的配置:spring.datasource.druid.stat-view-servlet;默认开启
  • DruidWebStatFilterConfiguration.class, web监控配置;spring.datasource.druid.web-stat-filter;默认开启
  • DruidFilterConfiguration.class}) 所有Druid自己filter的配置
    private static final String FILTER_STAT_PREFIX = "spring.datasource.druid.filter.stat";
    private static final String FILTER_CONFIG_PREFIX = "spring.datasource.druid.filter.config";
    private static final String FILTER_ENCODING_PREFIX = "spring.datasource.druid.filter.encoding";
    private static final String FILTER_SLF4J_PREFIX = "spring.datasource.druid.filter.slf4j";
    private static final String FILTER_LOG4J_PREFIX = "spring.datasource.druid.filter.log4j";
    private static final String FILTER_LOG4J2_PREFIX = "spring.datasource.druid.filter.log4j2";
    private static final String FILTER_COMMONS_LOG_PREFIX = "spring.datasource.druid.filter.commons-log";
    private static final String FILTER_WALL_PREFIX = "spring.datasource.druid.filter.wall";
1
2
3
4
5
6
7
8

# 配置示例

spring:
  datasource:
    url: jdbc:mysql://localhost:3306/maven
    username: root
    password: hsp
    driver-class-name: com.mysql.jdbc.Driver

    druid:
      filters: stat,wall               #底层开启功能,stat(sql监控),wall(防火墙)

      filter: 
        stat:                          #对上面filters里面的stat的详细配置
          slow-sql-millis: 1000
          logSlowSql: true
        wall:
          enabled: true
          config:
            drop-table-allow: false

      aop-patterns: com.frx01.admin.*  #监控SpringBean
      stat-view-servlet:               #配置监控页功能
        enabled: true
        login-username: admin
        login-password: 123456
        reset-enable: false

      web-stat-filter:                 # 监控web
        enabled: true
        exclusions: '*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*'
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

SpringBoot配置示例

https://github.com/alibaba/druid/tree/master/druid-spring-boot-starter

配置项列表https://github.com/alibaba/druid/wiki/DruidDataSource%E9%85%8D%E7%BD%AE%E5%B1%9E%E6%80%A7%E5%88%97%E8%A1%A8 (opens new window)

# 整合MyBatis操作

https://github.com/mybatis

starter

SpringBoot官方的Starter:spring-boot-starter-*

第三方的: *-spring-boot-starter

        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.4</version>
        </dependency>
1
2
3
4
5

02

# 配置模式

  • 全局配置文件
  • SqlSessionFactory: 自动配置好了
  • SqlSession:自动配置了 SqlSessionTemplate 组合了SqlSession
  • @Import(AutoConfiguredMapperScannerRegistrar.class);
  • Mapper: 只要我们写的操作MyBatis的接口标注了 @Mapper 就会被自动扫描进来
@EnableConfigurationProperties(MybatisProperties.class) : MyBatis配置项绑定类。
@AutoConfigureAfter({ DataSourceAutoConfiguration.class, MybatisLanguageDriverAutoConfiguration.class })
public class MybatisAutoConfiguration{}

@ConfigurationProperties(prefix = "mybatis")
public class MybatisProperties
1
2
3
4
5
6

可以修改配置文件中 mybatis 开始的所有;

#配置mybatis规则mybatis:

config-location: classpath:mybatis/mybatis-config.xml

mapper-locations: classpath:mybatis/mapper/*.xml

configuration:

map-underscore-to-camel-case: true

<?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="com.frx01.admin.mapper.EmployeeMapper">

    <!--public Employee getEmployee(Integer id);-->
    <select id="getEmployee" resultType="com.frx01.admin.bean.Employee">
        select * from tbl_employee where id=#{id}
    </select>
</mapper>
1
2
3
4
5
6
7
8
9
10
11

Mapper接口--->绑定xml--->操作数据库

配置 private Configuration configuration; mybatis.configuration下面的所有,就是相当于改mybatis全局配置文件中的值

#配置mybatis规则
mybatis:
#  config-location: classpath:mybatis/mybatis-config.xml
  mapper-locations: classpath:mybatis/mapper/*.xml
  configuration:
    map-underscore-to-camel-case: true
#可以不写全局;配置文件,所有全局配置文件的配置都放在configuration配置项中即可
1
2
3
4
5
6
7
  • 导入mybatis官方starter
  • 编写mapper接口。标准@Mapper注解
  • 编写sql映射文件并绑定mapper接口
  • 在application.yaml中指定Mapper配置文件的位置,以及指定全局配置文件的信息 (建议;配置在mybatis.configuration)

# 注解模式

  • 创建表并添加数据
CREATE TABLE city(
  id      INT(11) PRIMARY KEY AUTO_INCREMENT,
  `name`    VARCHAR(30),
  state   VARCHAR(30),
  country VARCHAR(30)
);	
INSERT INTO  city(`name`,state,country) VALUES('aaa','bbb','ccc')
1
2
3
4
5
6
7
  • Mapper层
/**
 * @author frx
 * @version 1.0
 * @date 2022/4/10  17:23
 */
@Mapper
public interface CityMapper {

    @Select("select * from city where id=#{id}")
    public City getById(Long id);
}
1
2
3
4
5
6
7
8
9
10
11
  • Bean层
@Data
public class City {

    private Long id;
    private String name;
    private String state;
    private String country;
}
1
2
3
4
5
6
7
8
  • Service层
@Service
public class CityService {

    @Autowired
    CityMapper cityMapper;

    public City getById(Long id){
        return cityMapper.getById(id);
    }
}
1
2
3
4
5
6
7
8
9
10
  • Controller层
@Controller
public class IndexController {

    @Autowired
    CityService cityService;

    @ResponseBody
    @GetMapping("/city")
    public City getCityById(@RequestParam("id") Long id){
        return cityService.getById(id);
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
  • 测试

03

# 混合模式

sql语句比较复杂

  • Mapper层
@Mapper
public interface CityMapper {

    @Select("select * from city where id=#{id}")
    public City getById(Long id);

    public void insert(City city);
}
1
2
3
4
5
6
7
8
<?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="com.frx01.admin.mapper.CityMapper">
    <!--public void insert(City city);-->
    <insert id="insert" useGeneratedKeys="true" keyProperty="id">
        insert into city(`name`,`state`,`country`) values(#{name},#{state},#{country})
    </insert>
</mapper>
1
2
3
4
5
6
7
8
9
10
  • Controller层
    @ResponseBody
	@PostMapping("/city")
    public City saveCity(City city){
        cityService.saveCity(city);
        return city;
    }
1
2
3
4
5
6
  • Service层
  public void saveCity(City city){
        cityMapper.insert(city);
    }
1
2
3

最佳实战:

  • 引入mybatis-starter
  • 配置application.yaml中,指定mapper-location位置即可
  • 编写Mapper接口并标注@Mapper注解
  • 简单方法直接注解方式
  • 复杂方法编写mapper.xml进行绑定映射
  • @MapperScan("com.atguigu.admin.mapper") 简化,其他的接口就可以不用标注@Mapper注解
#SpringBoot2
上次更新: 2024/04/21, 09:42:22
Web开发
单元测试

← Web开发 单元测试→

最近更新
01
微信支付功能的实现与流程
11-21
02
购物车与结算区域的深入优化与功能完善
11-21
03
购物车与结算区域的功能实现与优化
11-21
更多文章>
Theme by Vdoing | Copyright © 2023-2024 EmmmuaCode | 黔ICP备2022009864号-2
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式