mysql - 如何从我的 Spring Boot 应用程序在 mysql 中创建新架构

标签 mysql hibernate jpa spring-boot spring-data

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

我怎样才能做到这一点?

我正在使用hibernate,jpa

最佳答案

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

您可以使用以下代码来完成此操作:

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 的数据库。 请参阅“数据库”字段上的 @Value 注释。

关于mysql - 如何从我的 Spring Boot 应用程序在 mysql 中创建新架构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49442242/

相关文章:

php - 带复选框的多次更新 Laravel (LARAVEL 5.2)

java - Hibernate 和 Cayenne 的比较

java - JPA2 条件 : How to avoid a cross join using path. get()

java - 为什么在 Hibernate 抛出 ObjectNotFoundException 时 Spring 不抛出 DataAccessException?

带有规范的 Spring 可分页按连接列的顺序添加更多 LEFT JOIN

java - JPA - EmbeddedId 与@ManytoOne

php - 接受/拒绝提交按钮与 php 循环

mysql - Rails 服务器突然停止与 Mysql 一起工作并且无法连接

mysql - 这可以用mysql吗?

java - 如何为带注释和 hbm.xml 配置的实体创建 hibernate session bean