如何在我的Spring启动应用程序中在mysql中创建新架构

时间:2018-03-23 04:12:07

标签: mysql hibernate jpa spring-boot spring-data

我想在Spring启动时在mysql中创建新的数据库模式,因为它是通过命令行完成的 - > 创建数据库[schema-name]

我该如何实现?

我正在使用hibernate,jpa

1 个答案:

答案 0 :(得分:0)

我想你想以编程方式创建数据库。

您可以使用以下代码来完成此任务:

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;

@Component
public class ApplicationStartup implements ApplicationListener<ApplicationReadyEvent> {

    @Value("${database:DEMODB}")
    private String database;

    /**
     * This event is executed as late as conceivably possible to indicate that
     * the application is ready to service requests.
     */
    @Override
    public void onApplicationEvent(final ApplicationReadyEvent event) {

        // Defines the JDBC URL. As you can see, we are not specifying
        // the database name in the URL.
        String url = "jdbc:mysql://localhost";

        // Defines username and password to connect to database server.
        String username = "root";
        String password = "master";

        // SQL command to create a database in MySQL.
        String sql = "CREATE DATABASE IF NOT EXISTS " + database;

        try (Connection conn = DriverManager.getConnection(url, username, password);
             PreparedStatement stmt = conn.prepareStatement(sql)) {

            stmt.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}

确保在运行时通过组件扫描发现此组件。

您可以使用命令行传递数据库名称,如下所示:

  

java -jar spring-boot-app.jar --database = test_db

如果未指定数据库 - 此代码将创建名为DEMODB的DB。 请参阅&#39;数据库中的@Value注释。字段。