【笔记】创建一个初始化数据库的SpringBoot项目

前言

创建一个初始化数据库的SpringBoot项目,这个项目在运行时会自动执行所有sql文件内的所有sql语句

依赖

  • 编辑pom.xml配置文件
1
2
3
4
5
6
7
8
9
10
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>

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

配置数据库

  • 编辑applicationn.yml配置文件
1
2
3
4
5
6
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost/?useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT%2B8
username: root
password: 123456

准备sql文件

  • 将sql文件存放在/src/resources/sql/目录下

在启动类创建自动运行的方法

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
@SpringBootApplication
public class DemoApplication {

@Autowired
private DataSource dataSource;

public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}

@PostConstruct
public void init() throws SQLException {
exec("sql/account.sql");
exec("sql/storage.sql");
exec("sql/order.sql");
exec("sql/seata-server.sql");
}

private void exec(String sql) throws SQLException {
// 把脚本封装为资源对象
ClassPathResource classPathResource = new ClassPathResource(sql);
EncodedResource encodedResource = new EncodedResource(classPathResource, "utf-8");
// 使用Spring的ScriptUtils工具实现脚本执行
ScriptUtils.executeSqlScript(dataSource.getConnection(), encodedResource);
}

}

完成