I know that SchemaExport should be my friend. But I am using liquibase and want to execute the DDL - pure sql statements - generated from liquibase to recreate the database before every test method.
Do you see problems with the following code? I wonder that this seems to be so complicated ...
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: For liquibase you will need to do:
// 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");