2013-12-12 26 views
8

我需要這個集成測試。我的環境是JBoss 7,在Hibernate 4上使用JPA的EJB3,H2內存數據庫和測試由Arquillian運行。我希望能夠刪除數據庫並重新創建將基於persistence.xml和實體的所有表。我知道我可以通過指定的應用程序的啓動做:如何在Hibernate上手動調用JPA的創建 - 刪除?

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

但我需要從代碼中先降後手動做到這一點,創建發生。

可能嗎?什麼是最簡單的方法?

+0

您是否真的需要在測試之間重新創建模式,還是隻需要截斷數據? – FGreg

+0

@FGreg - 截斷所有數據並運行import.sql腳本就足夠了。解決方法存在,但我更感興趣,如果有一種方式來運行冬眠的方式... – sm4

+0

我不確定JUnit和Arquillian之間有什麼區別,但我有一個解決方案,用於截斷所有數據的JUnit每次測試後。如果你感興趣,我可以分享它,但我不知道它會有多大用處,因爲它非常依賴JUnit構造。 – FGreg

回答

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); 
     } 
    } 
} 
+0

您的scriptRunner可以使用Hibernate的ImportSqlCommandExtractor(http://docs.jboss.org/hibernate/core/4.1/javadocs/org/hibernate/tool/hbm2ddl/ImportSqlCommandExtractor.html)獲得更好的SQL解析(請參閱多行和單行提取器) 。乾杯 –

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

的Javadoc在這裏:

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

+0

這是否適合你?我已經試過了,但對db沒有影響 – mkn

相關問題