【问题标题】:loading DB driver in Global.beforeStart在 Global.beforeStart 中加载数据库驱动程序
【发布时间】:2014-03-21 09:52:57
【问题描述】:

我想在每次启动时执行一些数据库清理(在开发环境中完全删除和重新创建架构)。

我正在 Global.beforeStart 中执行此操作。而且因为它确实是开始之前我需要自己加载数据库驱动程序。

代码是:

    @Override
    public void beforeStart(Application app){
    System.out.println("IN beforeStart");
    try{
        Class.forName("org.postgresql.Driver");
        System.out.println("org.postgresql.Driver LOADED");
    } catch (ClassNotFoundException cnfe){
        System.out.println("NOT LOADED org.postgresql.Driver");
        cnfe.printStackTrace();
    }

    ServerConfig config = new ServerConfig();
    config.setName("pgtest");

    DataSourceConfig postgresDb = new DataSourceConfig ();
    postgresDb.setDriver("org.postgresql.Driver");
    postgresDb.setUsername("postgres");
    postgresDb.setPassword("postgrespassword");
    postgresDb.setUrl("postgres://postgres:postgrespassword@localhost:5432/TotoIntegration2");

    config.setDataSourceConfig(postgresDb);
    config.setDefaultServer(true);
    EbeanServer server = EbeanServerFactory.create(config);





    SqlQuery countTables = Ebean.createSqlQuery("select count(*) from  pg_stat_user_tables;");

    Integer numTables = countTables.findUnique().getInteger("count");
    System.out.println("numTables = " + numTables);
    if(numTables>2){
        DbHelper.cleanSchema();
    }
    System.out.println("beforeStart EXECUTED");
    //DbHelper.cleanSchema();

}

Class.forName("org.postgresql.Driver") 毫无例外地通过了,但是我得到了:

com.avaje.ebeaninternal.server.lib.sql.DataSourceException: java.sql.SQLException: 找不到适合 postgres 的驱动程序

就行 EbeanServer server = EbeanServerFactory.create(config);

为什么?

【问题讨论】:

标签: postgresql jdbc playframework ebean


【解决方案1】:

改用onStart,它在beforeStart 之后立即执行,但它是对数据库操作的自然候选(在生产模式下它不等待第一个请求),它们的javadoc:

/**
 * Executed before any plugin - you can set-up your database schema here, for instance.
 */
public void beforeStart(Application app) {
}

/**
 * Executed after all plugins, including the database set-up with Evolutions and the EBean wrapper.
 * This is a good place to execute some of your application code to create entries, for instance.
 */
public void onStart(Application app) {
}

请注意,您不需要在此处额外包含数据库配置,您可以在此处使用您的模型,就像在控制器中一样。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-31
    • 2011-07-06
    • 2016-12-02
    • 2012-09-17
    • 2016-02-07
    • 1970-01-01
    相关资源
    最近更新 更多