TruongPS
TruongPS

Reputation: 31

How to my Spring application connect to mySQL server on OpenShift?

In JPAConfiguration.java I use these below parameters to connect mySQL database. But it is not work. My application and mysql server is the same app on OpenShift.

private final String DATABASE_DRIVER = "com.mysql.jdbc.Driver";

private final String DATABASE_URL = "jdbc:mysql://"
            + System.getenv("OPENSHIFT_MYSQL_DB_HOST") + ":"
            + System.getenv("OPENSHIFT_MYSQL_DB_PORT") + "/"
            + "capsule";//System.getenv("OPENSHIFT_APP_NAME");

private final String DATABASE_USERNAME = System.getenv("OPENSHIFT_MYSQL_DB_USERNAME");
private final String DATABASE_PASSWORD = System.getenv("OPENSHIFT_MYSQL_DB_PASSWORD");

Please, give me some ideas. Thanks a lot.

Upvotes: 0

Views: 749

Answers (1)

Shekhar
Shekhar

Reputation: 5931

For Spring JPA applications,you have to define following datasource

@Bean(destroyMethod = "close")
public DataSource dataSource() {
    String username = System.getenv("OPENSHIFT_MYSQL_DB_USERNAME");
    String password = System.getenv("OPENSHIFT_MYSQL_DB_PASSWORD");
    String host = System.getenv("OPENSHIFT_MYSQL_DB_HOST");
    String port = System.getenv("OPENSHIFT_MYSQL_DB_PORT");
    String databaseName = System.getenv("OPENSHIFT_APP_NAME");
    String url = "jdbc:mysql://" + host + ":" + port + "/"+databaseName;
    BasicDataSource dataSource = new BasicDataSource();
    dataSource.setDriverClassName("org.MYSQL.Driver");
    dataSource.setUrl(url);
    dataSource.setUsername(username);
    dataSource.setPassword(password);
    dataSource.setTestOnBorrow(true);
    dataSource.setTestOnReturn(true);
    dataSource.setTestWhileIdle(true);
    dataSource.setTimeBetweenEvictionRunsMillis(1800000);
    dataSource.setNumTestsPerEvictionRun(3);
    dataSource.setMinEvictableIdleTimeMillis(1800000);
    dataSource.setValidationQuery("SELECT version()");

    return dataSource;
}

If you want to see a full working example then checkout my github repository https://github.com/shekhargulati/forumapp

Upvotes: 1

Related Questions