我想从 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/