0

I want to create new database schemas in mysql from spring boot as it is done with command line -> create database [schema-name]

How can I accomplish that?

I am using hibernate,jpa

Arul Rozario
  • 83
  • 10
  • Your questions is already answered here https://stackoverflow.com/questions/26881739/unable-to-get-spring-boot-to-automatically-create-database-schema – Sudhir Ojha Mar 23 '18 at 04:30
  • I want to specify the schema name dynamically based on some parameters. I think the link above is able to create a single schema. But I want to create multiple schemas. the schema names are dynamically generated. How do I accomplish that? – Arul Rozario Mar 23 '18 at 04:35
  • 1
    Possible duplicate of [Unable to get spring boot to automatically create database schema](https://stackoverflow.com/questions/26881739/unable-to-get-spring-boot-to-automatically-create-database-schema) – Mehraj Malik Mar 23 '18 at 05:50

1 Answers1

0

I suppose you want to create DB programmatically.

You can use the following code to accomplish that:

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

    }
}

Make sure this component will be discovered by component scan at runtime.

You can pass database name with command line as follows:

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

If no database specified - this code will create DB with name DEMODB. See @Value annotation over the 'database' field.

Eugene Maysyuk
  • 2,977
  • 25
  • 24