我知道SchemaExport應該是我的朋友。但我正在使用liquibase,並且想要執行DDL - 純粹的sql語句 - 從liquibase生成,以在每種測試方法之前重新創建數據庫。從休眠狀態執行DDL
您是否看到以下代碼存在問題?我不知道,這似乎是那麼複雜......
public static int executeScript(String sqlFileOnClasspath) {
Session sess = getSessionFactory().openSession();
Transaction ta = sess.beginTransaction();
int sqlCmd = 0;
try {
BufferedReader bReader = new BufferedReader(new InputStreamReader(
Util.class.getResourceAsStream(sqlFileOnClasspath), "UTF-8"));
String line;
while ((line = bReader.readLine()) != null) {
if (line.startsWith("--") || line.trim().isEmpty())
continue;
final String tmp = line;
sess.doWork(new Work() {
@Override
public void execute(Connection connection) throws SQLException {
connection.createStatement().execute(tmp);
}
});
sqlCmd++;
}
} catch (Exception ex) {
log.error("Couldn't execute " + sqlFileOnClasspath, ex);
} finally {
ta.commit();
sess.close();
}
return sqlCmd;
}
BTW:對於liquibase你需要做的:
// remove all hibernate managed tables
SchemaExport schemaTool = new SchemaExport(getConfiguration());
schemaTool.drop(false, true);
// DROP TABLE DATABASECHANGELOGLOCK;
// DROP TABLE DATABASECHANGELOG;
executeScript("/drop-none-hib.sql");
// now execute the DDL statements from liquibase
int sqlCmd = executeScript("/schema.sql");
log.info("Executed " + sqlCmd + " sql commands");
很酷,非常感謝!對於TA處理:我希望你知道它;-) – Karussell 2010-07-10 21:31:22
當一個DDL執行成功時,一個COMMIT被隱式執行,所以你不能手動回滾。但是,如果DDL錯誤,它會自動回滾(例如,DROP TABLE將執行成功並且該表永遠消失,或者它不會工作,表存在且處於一致狀態)http://searchoracle.techtarget。 com/answer/Do-DDL-statements-roll-back-and-why – mhaller 2010-07-10 21:37:45
再次感謝! (目前鏈接不工作:-() – Karussell 2010-07-11 21:45:48