前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >SpringBoot高级篇DB之基本使用

SpringBoot高级篇DB之基本使用

作者头像
一灰灰blog
修改2019-03-15 09:13:54
1.2K0
修改2019-03-15 09:13:54
举报
文章被收录于专栏:小灰灰小灰灰

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

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

<!-- more -->

I. 基本配置

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

1. 依赖配置

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

代码语言:txt
复制
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
</dependency>

2. 配置

测试的MySql的配置如下

代码语言:txt
复制
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=

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

代码语言:txt
复制
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;

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

II. 使用实例

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

1. 测试代码

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

代码语言:txt
复制
@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);
    }
}

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

2. 结果截图

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

测试结果
测试结果

3. 默认配置分析

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

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

代码语言:txt
复制
# 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.

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

代码语言:txt
复制
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.

从上面可以看出,并没有给默认值,所以我们想要使用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. 项目

1. 一灰灰Blog

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

2. 声明

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

3. 扫描关注

一灰灰blog

QrCode
QrCode

知识星球

goals
goals

本文系转载,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文系转载前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • I. 基本配置
    • 1. 依赖配置
      • 2. 配置
      • II. 使用实例
        • 1. 测试代码
          • 2. 结果截图
            • 3. 默认配置分析
            • III. 小结
            • IV. 其他
              • 0. 项目
                • 1. 一灰灰Blog
                  • 2. 声明
                    • 3. 扫描关注
                    相关产品与服务
                    云数据库 SQL Server
                    腾讯云数据库 SQL Server (TencentDB for SQL Server)是业界最常用的商用数据库之一,对基于 Windows 架构的应用程序具有完美的支持。TencentDB for SQL Server 拥有微软正版授权,可持续为用户提供最新的功能,避免未授权使用软件的风险。具有即开即用、稳定可靠、安全运行、弹性扩缩等特点。
                    领券
                    问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档