1

I would like to create a table in database where database name is not known before. At runtime, user creates database what is the best way to switch database at runtime keeping only one hibernate configuration file ?

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.

Any help is greatly appriciated.

1 Answer 1

1

We create new databases dynamically:

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);
                }
            });

It uses schema template where we have all the tables definitions.

Then we build configuration and session factory:

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 file:

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

where DeviceData is regular hibernate bean:

@Entity
@Table(name="device_data")
public class DeviceData {
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.