如何在Hibernate上从JPA手动调用create-drop?

时间:2013-12-12 05:01:39

标签: java hibernate jpa jboss-arquillian

我需要这个进行集成测试。我的环境是JBoss 7,在Hibernate 4上使用JPA的EJB3,H2内存数据库和测试由Arquillian运行。我希望能够删除数据库并再次创建它将基于persistence.xml和实体的所有表。我知道我可以在应用程序开始时指定:

<property name="hibernate.hbm2ddl.auto" value="create-drop" /> 

但是我需要在第一次删除后手动从代码中手动执行此操作并创建。

有可能吗?什么是最简单的方法?

3 个答案:

答案 0 :(得分:3)

您可以在Hibernate中以编程方式执行此操作。

config = new Configuration();
config.setProperty(org.hibernate.cfg.Environment.SHOW_SQL, "true");
config.setProperty(org.hibernate.cfg.Environment.HBM2DDL_AUTO, "create");
....
SchemaExport export = new SchemaExport( config );
export.create( true, true );

JavaDocs在这里:

http://docs.jboss.org/hibernate/core/3.5/javadocs/org/hibernate/cfg/Configuration.html http://docs.jboss.org/hibernate/orm/3.5/javadocs/org/hibernate/tool/hbm2ddl/SchemaExport.html

答案 1 :(得分:1)

您可以使用Arquillian持久性扩展在每次测试后使用测试方法上的@UsingDataSet注释清除数据库内容:https://github.com/arquillian/arquillian-extension-persistence

答案 2 :(得分:0)

我认为您需要手动创建脚本。然后,您可以使用ScriptRunner(复制项目中的类):

public class YourIntegrationTestClass {
    private String url = "test-db-url";
    private String user = "user";
    private String pass = "pass";

    // run this before the test
    public void prepareDB() {
        // executes a script stored in test/resources/cucumber
        try {
            // use your driver here
            Class.forName("com.mysql.jdbc.Driver");
            Connection conn = DriverManager.getConnection(url, user, pass);
            ScriptRunner runner = new ScriptRunner(conn, false, true);

            // use your db creation script here
            runner.runScript(new BufferedReader(new FileReader("createDB.sql")));
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage(), e);
        }
    }

    // run this after the tests
    public void dropDB() {
            // use your driver here
            Class.forName("com.mysql.jdbc.Driver");
            Connection conn = DriverManager.getConnection(url, user, pass);
            ScriptRunner runner = new ScriptRunner(conn, false, true);

            // use your db drop script here
            runner.runScript(new BufferedReader(new FileReader("dropDB.sql")));
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage(), e);
        }
    }
}