From b7da3af75061f67320841be84bed13a218d23752 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=9C=A8=E5=AD=90=E6=9D=8E=C2=B7De?= Date: Mon, 5 Jul 2021 13:34:16 +0800 Subject: [PATCH] DatabaseInitializer --- .../business/config/DatabaseInitializer.java | 54 +++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 report-core/src/main/java/com/anjiplus/template/gaea/business/config/DatabaseInitializer.java diff --git a/report-core/src/main/java/com/anjiplus/template/gaea/business/config/DatabaseInitializer.java b/report-core/src/main/java/com/anjiplus/template/gaea/business/config/DatabaseInitializer.java new file mode 100644 index 00000000..be4afc9f --- /dev/null +++ b/report-core/src/main/java/com/anjiplus/template/gaea/business/config/DatabaseInitializer.java @@ -0,0 +1,54 @@ +package com.anjiplus.template.gaea.business.config; + +import com.zaxxer.hikari.HikariDataSource; +import lombok.AllArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.boot.autoconfigure.flyway.FlywayProperties; +import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties; +import org.springframework.stereotype.Component; + +import javax.annotation.PostConstruct; +import java.sql.Connection; +import java.sql.SQLException; +import java.sql.Statement; + +/** + * Created by raodeming on 2021/7/5. + */ +@Slf4j +@Component +@AllArgsConstructor +public class DatabaseInitializer { + + private final FlywayProperties flywayProperties; + private final DataSourceProperties dataSourceProperties; + + @PostConstruct + public void init() throws SQLException { + log.info("DatabaseInitializer uses flyway init-sqls to initiate database"); + String url = dataSourceProperties.getUrl(); + // jdbc url最后一个 '/' 用于分割具体 schema?参数 + int lastSplitIndex = url.lastIndexOf('?'); + // 获取spring.datasource.url具体数据库schema前的jdbc url + String addressUrl = url.substring(0, lastSplitIndex); + String addresslast = url.substring(lastSplitIndex); + addressUrl = addressUrl.substring(0, addressUrl.lastIndexOf("/")); + // 直连数据库地址:jdbc:mysql://yourIp:port + HikariDataSource dataSource = new HikariDataSource(); + dataSource.setJdbcUrl(addressUrl.concat(addresslast)); + dataSource.setUsername(dataSourceProperties.getUsername()); + dataSource.setPassword(dataSourceProperties.getPassword()); + Connection connection = dataSource.getConnection(); + Statement statement = connection.createStatement(); + for (String sql : flywayProperties.getInitSqls()) { + // 通过flyway的init-sqls配置进行建库与数据库配置 + // executeUpdate:执行给定的SQL语句,该语句可以是INSERT,UPDATE或DELETE语句或不返回任何内容的SQL语句,例如SQL DDL语句。 + statement.executeUpdate(sql); + } + statement.close(); + connection.close(); + dataSource.close(); + log.info("DatabaseInitializer initialize completed"); + } + +}