一灰灰blog 一灰灰blog
首页
  • InfluxDB
  • MongoDB
  • MySql
  • 基础系列
  • DB系列
  • 搜索系列
  • MQ系列
  • WEB系列
  • 中间件
  • 运维
  • SpringSecurity
  • SpringCloud
  • QuickAlarm
  • QuickCrawer
  • QuickFix
  • QuickMedia
  • QuickSpi
  • QuickTask
  • 高可用
  • 分类
  • 标签
  • 归档
  • 收藏
  • 关于
GitHub (opens new window)

一灰灰blog

资深搬运工
首页
  • InfluxDB
  • MongoDB
  • MySql
  • 基础系列
  • DB系列
  • 搜索系列
  • MQ系列
  • WEB系列
  • 中间件
  • 运维
  • SpringSecurity
  • SpringCloud
  • QuickAlarm
  • QuickCrawer
  • QuickFix
  • QuickMedia
  • QuickSpi
  • QuickTask
  • 高可用
  • 分类
  • 标签
  • 归档
  • 收藏
  • 关于
GitHub (opens new window)
  • 基础系列

  • DB系列

    • H2Database

    • JPA

    • JdbcTemplate

    • Jooq

    • Mybatis

    • 事务

    • MongoDB

    • Redis

    • 实例

      • 【DB系列】DB之基本使用
        • I. 基本配置
          • 1. 依赖配置
          • 2. 配置
        • II. 使用实例
          • 1. 测试代码
          • 2. 结果截图
          • 3. 默认配置分析
        • III. 小结
        • IV. 其他
          • 0. 项目
          • 1. 一灰灰Blog
          • 2. 声明
          • 3. 扫描关注
      • 【DB系列】SpringBoot+Mysql 无法保存emoj表情
  • 搜索系列

  • MQ系列

  • WEB系列

  • 中间件

  • 运维

  • SpringSecurity

  • SpringCloud

  • Spring系列
  • DB系列
  • 实例
一灰灰
2018-09-26

【DB系列】DB之基本使用

现在的完整的后端项目,基本上离不开DB、缓存,接下来开始进入DB篇的系列教程,首先确定我们的目标,一个是知道怎么配置,怎么用;接着就是更高级一点的多个数据源的配置,使用不同的方式来实现CURD(如Mybatis, JPDA, MyCat, Hibernate, Jooq等),数据库不得不谈到的事物管理,锁机制,以及高级一点的分库分表等;然后再进一步则是优秀的框架的学习了,大名鼎鼎的MyBaits的设计思路,Jooq的使用姿势也特别有意思

要学习的东西不少,要写的内容也挺多,先一步步来,本篇主要目的是先搭建一个可以跑DB的基础Demo,为后续的博文开开胃

# I. 基本配置

首先确认我们的DB采用的是MySql数据库,我们这里通过JdbcTemplate来对DB内容进行操作演示;在开始之前,请先准备好Mysql的安装以及相关配置,下面我们默认已经备好

# 1. 依赖配置

对于SpringBoot而言,要想操作DB,需要引入如下的依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
</dependency>
1
2
3
4
5
6
7
8
9

# 2. 配置

测试的MySql的配置如下

spring.datasource.url=jdbc:mysql://127.0.0.1:3306/story?useUnicode=true&characterEncoding=UTF-8&useSSL=false
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.username=root
spring.datasource.password=
1
2
3
4

测试的库名为story, 表名为Subcribe,表结构如下

CREATE TABLE `Subscribe` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `email` varchar(40) NOT NULL DEFAULT '',
  `nick` varchar(30) NOT NULL DEFAULT '',
  `status` tinyint(4) NOT NULL DEFAULT '0' COMMENT '0 订阅未激活, 1 订阅已激活 , 2 取消订阅',
  `created` int(13) NOT NULL DEFAULT '0' COMMENT '创建时间',
  `updated` int(13) NOT NULL DEFAULT '0' COMMENT '更新时间',
  `extra` varchar(64) NOT NULL DEFAULT '' COMMENT '扩展信息',
  `channel` int(4) NOT NULL DEFAULT '0' COMMENT '渠道, 0古诗,1博客',
  PRIMARY KEY (`id`),
  UNIQUE KEY `email` (`email`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8mb4;
1
2
3
4
5
6
7
8
9
10
11
12

到此配置基本完成,具体到我们的项目中,也就是pom中添加两个依赖,设置下properties文件中的参数,然后就可以愉快的使用了

# II. 使用实例

前面配置完成,接着就来测试,看下是否就真的可以用了

# 1. 测试代码

直接用比较简单的JdbcTemplate来实现db的操作,至于如何获取这个实例呢?直接注入即可(后面说原因)

@Slf4j
@SpringBootApplication
public class Application {

    public Application(JdbcTemplate jdbcTemplate) {
        List<Map<String, Object>> result = jdbcTemplate.queryForList("select * from Subscribe limit 2");
        log.info("result: {}", result);
    }

    public static void main(String[] args) {
        SpringApplication.run(Application.class);
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13

因为我们的项目结构比较简单,没有引入web的依赖,所以就把JdbcTemplate的测试放在了Application的构造方法中;执行完毕之后,项目就结束;而这个JdbcTemplate实例,则是由Spring框架来初始化,并注入的

# 2. 结果截图

整个测试DB使用的项目就完成了,相比较之前的Spring时代,少了n多的xml配置和pom引入,简单了不少,下面是执行的截图

测试结果

# 3. 默认配置分析

前面讲配置的博文中,也说到了SpringBoot也一套默认的配置,具体博文可以查看: 180925-SpringBoot基础篇配置信息之默认配置 (opens new window)

我们来看一下db相关的默认属性为

# DATASOURCE (DataSourceAutoConfiguration & DataSourceProperties)
spring.datasource.continue-on-error=false # Whether to stop if an error occurs while initializing the database.
spring.datasource.data= # Data (DML) script resource references.
spring.datasource.data-username= # Username of the database to execute DML scripts (if different).
spring.datasource.data-password= # Password of the database to execute DML scripts (if different).
spring.datasource.dbcp2.*= # Commons DBCP2 specific settings
spring.datasource.driver-class-name= # Fully qualified name of the JDBC driver. Auto-detected based on the URL by default.
spring.datasource.generate-unique-name=false # Whether to generate a random datasource name.
spring.datasource.hikari.*= # Hikari specific settings
spring.datasource.initialization-mode=embedded # Initialize the datasource with available DDL and DML scripts.
spring.datasource.jmx-enabled=false # Whether to enable JMX support (if provided by the underlying pool).
spring.datasource.jndi-name= # JNDI location of the datasource. Class, url, username & password are ignored when set.
spring.datasource.name= # Name of the datasource. Default to "testdb" when using an embedded database.
spring.datasource.password= # Login password of the database.
spring.datasource.platform=all # Platform to use in the DDL or DML scripts (such as schema-${platform}.sql or data-${platform}.sql).
spring.datasource.schema= # Schema (DDL) script resource references.
spring.datasource.schema-username= # Username of the database to execute DDL scripts (if different).
spring.datasource.schema-password= # Password of the database to execute DDL scripts (if different).
spring.datasource.separator=; # Statement separator in SQL initialization scripts.
spring.datasource.sql-script-encoding= # SQL scripts encoding.
spring.datasource.tomcat.*= # Tomcat datasource specific settings
spring.datasource.type= # Fully qualified name of the connection pool implementation to use. By default, it is auto-detected from the classpath.
spring.datasource.url= # JDBC URL of the database.
spring.datasource.username= # Login username of the database.
spring.datasource.xa.data-source-class-name= # XA datasource fully qualified name.
spring.datasource.xa.properties= # Properties to pass to the XA data source.
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

上面的默认配置中东西挺多的,首先需要过滤出我们必要的几个参数

spring.datasource.driver-class-name= # Fully qualified name of the JDBC driver. Auto-detected based on the URL by default.
spring.datasource.url= # JDBC URL of the database.
spring.datasource.username= # Login username of the database.
spring.datasource.password= # Login password of the database.
spring.datasource.name= # Name of the datasource. Default to "testdb" when using an embedded database.
1
2
3
4
5

从上面可以看出,并没有给默认值,所以我们想要使用MySql,就必须填上必要的参数了(url, usernmae必须的),即我们只设置这两个参数,项目就可以愉快的玩耍了 (工程源码中只保留了两个基本参数)

# III. 小结

本篇内容相对简单,主要介绍了如何使用SpringBoot搭建一个简单的可读写DB的示例DEMO,总得来说,配置很简单了

  • pom依赖引入:spring-boot-starter-jdbc, mysql-connector-java
  • 数据库配置指定:spring.datasource.url, spring.datasource.username 这两个参数为必选
  • 注入JdbcTemplate开始使用

第一步是搭建起来了,接下来自然而然就有几个问题了

  • 如果项目需要连接多个不同的数据库怎么办?
  • JdbcTemplate操作DB的方式不太简单,用更高级的方式可以怎么玩?
  • 听说druid号称是java中最好的数据库连接池,那这个到底是啥,要怎么用?有没有其他类似的东西呢?
  • 关于db的使用相关姿势问题....

基础环境搭建好,接下来开始上菜

# IV. 其他

# 0. 项目

  • 工程:spring-boot-demo (opens new window)

# 1. 一灰灰Blog

  • 一灰灰Blog个人博客 https://blog.hhui.top (opens new window)
  • 一灰灰Blog-Spring专题博客 http://spring.hhui.top (opens new window)

一灰灰的个人博客,记录所有学习和工作中的博文,欢迎大家前去逛逛

# 2. 声明

尽信书则不如,已上内容,纯属一家之言,因个人能力有限,难免有疏漏和错误之处,如发现bug或者有更好的建议,欢迎批评指正,不吝感激

  • 微博地址: 小灰灰Blog (opens new window)
  • QQ: 一灰灰/3302797840

# 3. 扫描关注

一灰灰blog

QrCode

知识星球

goals

编辑 (opens new window)
#DB#MySql
上次更新: 2021/10/15, 19:56:22
【DB系列】Redis实现分布式锁(应用篇)
【DB系列】SpringBoot+Mysql 无法保存emoj表情

← 【DB系列】Redis实现分布式锁(应用篇) 【DB系列】SpringBoot+Mysql 无法保存emoj表情→

最近更新
01
【基础系列】基于maven多环境配置
04-25
02
【WEB系列】内嵌Tomcat配置Accesslog日志文件生成位置源码探索
04-24
03
【搜索系列】ES查询常用实例演示
04-18
更多文章>
Theme by Vdoing | Copyright © 2017-2022 一灰灰Blog
MIT License | 鄂ICP备18017282号 |
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式
×