Spring Boot中初始化MySQL

目标

简单介绍一下SpringBoot中简单配置MySQL的过程。

Spring

pom.xml

	<properties>
		<java.version>1.8java.version>
		<spring-mybatis.version>2.3.1spring-mybatis.version>
	properties>
...
		<dependency>
			<groupId>org.mybatis.spring.bootgroupId>
			<artifactId>mybatis-spring-boot-starterartifactId>
			<version>${spring-mybatis.version}version>
		dependency>
...

因为这里的SpringBoot2.6.4版本,根据spring-boot-starter官网,应当选择2.3.x版本的spring-boot-starter。具体参考如下:
Spring Boot中初始化MySQL_第1张图片

application-dev.yaml

spring:
  datasource:
    url: jdbc:mysql://${MYSQL_HOST:localhost}:3306/dbname?characterEncoding=UTF-8&connectionTimeZone=GMT%2B8&forceConnectionTimeZoneToSession=true
    username: ${MYSQL_USERNAME:username}
    password: ${MYSQL_PASSWORD}

MYSQL_PASSWORD最好别配置默认值。

MySQL

create database dbname default character set utf8mb4 collate utf8mb4_unicode_ci;
create user 'username'@'%' IDENTIFIED BY 'password';
GRANT ALL PRIVILEGES ON dbname.* TO 'username'@'%';
FLUSH PRIVILEGES;

测试

Springboot mybatis启动结果,下图表示启动成功:
Spring Boot中初始化MySQL_第2张图片

参考:

  • MySQL8分配只读用户
  • MySQL建库
  • spring-boot-starter

你可能感兴趣的:(mysql,spring,boot,java,mybatis)