gpt4 book ai didi

java - hibernate中的动态数据库名称

转载 作者:行者123 更新时间:2023-11-30 06:46:04 24 4
gpt4 key购买 nike

我想在数据库中创建一个表,其中数据库名称之前未知。在运行时,用户创建数据库,在运行时切换数据库只保留一个 hibernate 配置文件的最佳方法是什么?

For Example, system creates database 'Random1' and I would like to create table A in 'Random1' databse. What is the best way to do it? Here table A definition is known before.

非常感谢任何帮助。

最佳答案

我们动态创建新数据库:

session.doWork(new Work() {
@Override
public void execute(Connection connection) throws SQLException {
boolean autoCommit = connection.getAutoCommit();
connection.setAutoCommit(true);
Statement stmt = connection.createStatement();
stmt.executeUpdate("CREATE DATABASE " + dbName + " WITH TEMPLATE my_template ENCODING 'UTF8'");

// set this back to previous value before returning connection to the pool
connection.setAutoCommit(autoCommit);
}
});

它使用架构模板,我们在其中拥有所有表定义。

然后我们构建配置和 session 工厂:

public static Configuration buildConfiguration(String serverName, String databaseName) {
return createConfiguration()
.setProperty("connection.url", "jdbc:postgresql://" + serverName + ":5432/" + databaseName)
}

private static Configuration createConfiguration() {
Configuration configuration = new Configuration().configure(HIBERNATE_CFG_XML_FILE);
return configuration;
}

configuration.buildSessionFactory();

hibernate xml 文件:

<hibernate-configuration>
<session-factory>
<mapping class="com.crowdoptic.database.clustersdata.DeviceData"/>
</session-factory>

其中 DeviceData 是常规 hibernate bean:

@Entity
@Table(name="device_data")
public class DeviceData {

关于java - hibernate中的动态数据库名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43666331/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com