当先锋百科网

首页 1 2 3 4 5 6 7

springboot项目预加载mysql数据库

操作流程

1. 总体思路

springboot项目启动,判断是否存在数据库,如果没有,则创建数据库并导入sql文件,如果有则不导入.

2. YML配置

#需要加载的数据库名称
targetDBName: rep_dev666
server:
  port: 9000
spring:
  datasource:
    driverClassName: com.mysql.cj.jdbc.Driver
    username: root
    password: 'password'
    url: jdbc:mysql://192.168.0.200:3306/${targetDBName}?useUnicode=true&characterEncoding=utf8&serverTimezone=Asia/Shanghai&rewriteBatchedStatements=true
    #类路径下(resource/sql录下放置sql文件)
    schema: classpath:sql/mysql-demo.sql

3. 注册组件

@Component
public class CustomizeDataSourceInitializer implements InitializingBean {

    private static final Logger LOG = LoggerFactory.getLogger(CustomizeDataSourceInitializer.class);

    /**
     * com.mysql.cj.jdbc.Driver
     */
    @Value("${spring.datasource.driverClassName}")
    private String driver;
    /**
     * jdbc_url
     */
    @Value("${spring.datasource.url}")
    private String url;
    /**
     * 账号名称
     */
    @Value("${spring.datasource.username}")
    private String username;
    /**
     * 账号密码
     */
    @Value("${spring.datasource.password}")
    private String password;

    /**
     * 需要创建的数据名称
     */
    @Value("${targetDBName}")
    private String targetDBName;


    @Autowired
    ApplicationContext applicationContext;

    @Override
    public void afterPropertiesSet() throws Exception {
        initTableSchema();
    }

    private void initTableSchema() throws SQLException {

        URI uri = null;
        try {
            Class.forName(driver);
            uri = new URI(url.replace("jdbc:", ""));
        } catch (ClassNotFoundException | URISyntaxException e) {
            LOG.error("JDBC URL解析错误", e);
        }
        String host = uri.getHost();
        int port = uri.getPort();


        DataSource dataSource = applicationContext.getBean(DataSource.class);

        try (Connection connection = DriverManager.getConnection("jdbc:mysql://" + host + ":" + port +
                "?useUnicode=true&characterEncoding=UTF-8&useSSL=false", username, password);
             Statement statement = connection.createStatement();
             Reader resourceAsReader = Resources.getResourceAsReader("sql/mysql-demo.sql");
        ) {
            String sql = "select schema_name from information_schema.schemata where schema_name = " + "'" + targetDBName + "'";
            //查询返回的结果集
            ResultSet resultSet = statement.executeQuery(sql);
            if (!resultSet.next()) {
                //查不到数据库,执行数据库初始化脚本
                LOG.warn("不存在数据库({})", targetDBName);
                LOG.warn("==================开始创建数据库==================");
                String createDb = "CREATE DATABASE IF NOT EXISTS " + targetDBName;
                connection.setAutoCommit(false);
                statement.execute(createDb);
                connection.commit();
                LOG.warn("创建数据库({})成功", targetDBName);

                Connection connection2 = dataSource.getConnection();

                LOG.warn("==================现在初始化脚本==================");
                ScriptRunner runner = new ScriptRunner(connection2);
                runner.runScript(resourceAsReader);
                LOG.warn("==================脚本初始化完成==================");
            } else {
                LOG.warn("=================已经存在数据库===================");
            }
        } catch (IOException | SQLException e) {
            LOG.error("========================mysql建表异常===================");
        }
    }
}

总结

至此,可以实现预加载数据库文件. 以上代码,存在一些异常不足,待优化.