SpringBoot项目数据库访问MySQL

SpringBoot项目数据库访问MySQL

此项目以MySQL数据库作为测试数据库,并使用Flyway来管理数据库版本。

先要安装好MySQL数据库,然后建立测试数据库user_db,我们使用Flyway来管理数据库版本,因此不用建表,直接通过Flyway脚本sql来见表,并自动维护好数据库表结构版本信息。

新建项目

参考基本配置文章:https://fugary.com/?p=51

用https://start.spring.io来建立新项目,然后配置成继承通用的父级项目。

新建项目

项目名称simple-boot-mysql-demo,源码地址:

主要要引入,MySQL、Flyway、Lombok、MyBatis等。

项目基本配置

然后把生成的项目复制到我们的工程之中,并在父级项目中配置module

<module>simple-boot-mysql-demo</module>

项目pom.xml

<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
   <modelVersion>4.0.0</modelVersion>
   <parent>
      <groupId>com.mengstudy</groupId>
      <artifactId>simple-boot-parent</artifactId>
      <version>0.0.1-SNAPSHOT</version>
   </parent>
   <artifactId>simple-boot-mysql-demo</artifactId>
   <version>0.0.1-SNAPSHOT</version>
   <name>simple-boot-mysql-demo</name>
   <description>MySQL 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-web</artifactId>
      </dependency>
      <dependency>
         <groupId>org.flywaydb</groupId>
         <artifactId>flyway-core</artifactId>
      </dependency>
      <dependency>
         <groupId>org.mybatis.spring.boot</groupId>
         <artifactId>mybatis-spring-boot-starter</artifactId>
      </dependency>
      <dependency>
         <groupId>com.baomidou</groupId>
         <artifactId>mybatis-plus-boot-starter</artifactId>
      </dependency>
      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-devtools</artifactId>
         <scope>runtime</scope>
         <optional>true</optional>
      </dependency>
      <dependency>
         <groupId>mysql</groupId>
         <artifactId>mysql-connector-java</artifactId>
         <scope>runtime</scope>
      </dependency>
      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-configuration-processor</artifactId>
         <optional>true</optional>
      </dependency>
      <dependency>
         <groupId>org.projectlombok</groupId>
         <artifactId>lombok</artifactId>
         <optional>true</optional>
      </dependency>
      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-test</artifactId>
         <scope>test</scope>
         <exclusions>
            <exclusion>
               <groupId>org.junit.vintage</groupId>
               <artifactId>junit-vintage-engine</artifactId>
            </exclusion>
         </exclusions>
      </dependency>
   </dependencies>
   <build>
      <plugins>
         <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
         </plugin>
      </plugins>
   </build>
</project>

application.yml配置

server:
  port: 8080
spring:
  application:
    name: simple-boot-mysql-demo
  datasource:
    type: com.zaxxer.hikari.HikariDataSource
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost:3306/user_db?useUnicode=true&characterEncoding=UTF-8
    username: root
    password: 123456
    hikari: # 连接池配置
      maximum-pool-size: 30
      minimum-idle: 2
      connection-test-query: select 1;
  flyway:
    baseline-on-migrate: true
    out-of-order: true
    #很多都是默认配置,并不需要配置
    placeholder-prefix: "${"
    table: flyway_schema_history
    locations: classpath:db/migration

项目Flyway管理

由于我们使用了flyway来管理版本,默认flyway的sql文件存放位置:classpath:db/migration文件夹下面。

配置spring.flyway.baseline-on-migrate=true,把第一个版本为baseline,也就是数据库基线,如果此数据库已经有很多表结构和数据的情况下需要配置好基线,方便新的结构和版本管理

项目脚本数据

这些脚本的文件可以自定义,但是是按照Flyway脚本的格式来编写:版本号__版本描述.sql,版本号用下划线分隔小版本的值。

V1_0_0__db schema.sql:

DROP TABLE IF EXISTS t_user;
CREATE TABLE `t_user` (
  `id` bigint not null,
  `user_name` varchar(100) NOT NULL,
  `nick_name` varchar(100) DEFAULT NULL,
  `birth` timestamp DEFAULT NULL,
  `user_password` varchar(1024) DEFAULT NULL,
  `user_status` int DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;

V1_0_1__db mock data.sql:

DELETE FROM t_user;
INSERT INTO `t_user`(`id`, `user_name`, `nick_name`, `birth`, `user_password`, `user_status`)
VALUES (1, 'gary', 'Gary', '2000-01-01', '123456', 1),
(2, 'jerry', 'Jerry', '2000-01-02', '123456', 1), 
(3, 'tom', 'Tom', '2000-01-03', '123456', 1);

Flyway配置说明

一般使用默认配置即可,详细的默认值可以参考文件FlywayProperties的构造方法:org.springframework.boot.autoconfigure.flyway.FlywayProperties#FlywayPropertie()

public FlywayProperties() {
    this.encoding = StandardCharsets.UTF_8;
    this.schemas = new ArrayList();
    this.table = "flyway_schema_history"; // 默认的表名称,会自动建立
    this.baselineDescription = "<< Flyway Baseline >>"; // base line 描述
    this.baselineVersion = "1";
    this.placeholders = new HashMap();
    this.placeholderPrefix = "${";    // 如果参数占位,有可能会和maven等冲突,因此可能需要自定义,如:@{
    this.placeholderSuffix = "}";
    this.placeholderReplacement = true;
    this.sqlMigrationPrefix = "V";
    this.sqlMigrationSuffixes = new ArrayList(Collections.singleton(".sql"));
    this.sqlMigrationSeparator = "__"; // sql格式,版本号和描述分隔符配置,如:V1_0_1__一些描述.sql
    this.repeatableSqlMigrationPrefix = "R";
    this.initSqls = new ArrayList();
    this.ignoreFutureMigrations = true;
    this.validateOnMigrate = true;
}

其他说明:

spring:
  flyway:
    baseline-on-migrate: true #是否建立baseline
    out-of-order: true #版本是否是无序,建议是开启,尤其是多人开发的时候,后提交老版本的sql也能得到执行
    locations: classpath:db/migration #默认位置
暂无评论

发送评论 编辑评论


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇
下一篇