Search code examples
mysqlplayframeworkplayframework-2.5playframework-evolutionsdeadbolt-2

Create database play java evolutions


I am using play java 2.5. I have created a database with following java code.

public OnStartup() throws SQLException {
    //demo create database with java code
    Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/?user=root&password=12345678");
    Statement s = con.createStatement();
    int Result = s.executeUpdate("CREATE DATABASE recruit3");
}

Module:

public class OnStartupModule extends AbstractModule {
    @Override
    public void configure() {
        bind(OnStartup.class).asEagerSingleton();
    }
}

application.conf:

play.modules {
    enabled += "be.objectify.deadbolt.java.DeadboltModule"
    enabled += modules.CustomDeadboltHook
    enabled += modules.OnStartupModule 
}

default.driver=com.mysql.jdbc.Driver
default.url="jdbc:mysql://localhost:3306/recruit3"
default.username=root
default.password="12345678"

My question is, why running the web-app creating

error Cannot connect to database [default]

How to fix that, if I don't want to create the database with mysql workbench.

Any suggestion or cannot do this, please tell me. Thanks for advance.


Solution

  • As well as moving your database keys to the db.default namespace, you should be injecting Database into OnStartup to access the database configured with those properties.

    First, add Play's JDBC support to build.sbt.

    libraryDependencies += javaJdbc
    

    If you're already running activator, make sure you use the reload command to pick up the changes to the build.

    Update your application.conf to place the database configuration into the correct namespace.

    db {
      default {
        driver=com.mysql.jdbc.Driver
        url="jdbc:mysql://localhost:3306/recruit3"
        username=root
        password="12345678"
      }    
    }
    

    Finally, update OnStartup to receive a Database object that will be injected by Play.

    import javax.inject.Inject;
    import play.db.Database;
    
    public class OnStartup {
    
        @Inject
        public OnStartup(final Database db) throws SQLException {
            db.withConnection((Connection conn) -> {
                final Statement s = con.createStatement();
                return s.executeUpdate("CREATE DATABASE recruit3");
            });
        }
    }
    

    This allows you to configure the database one time, in application.conf, instead of hard-coding DB configuration into a class.

    You can find more information here.