【发布时间】:2010-07-10 21:09:36
【问题描述】:
我知道 SchemaExport 应该是我的朋友。但我正在使用 liquibase 并希望执行从 liquibase 生成的 DDL(纯 sql 语句),以便在每个测试方法之前重新创建数据库。
您是否发现以下代码存在问题?我想知道这似乎如此复杂......
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;
}
顺便说一句:对于 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");
【问题讨论】: