static Map<ProcessEngine, String[]> cleanSqlCache = new HashMap<ProcessEngine, String[]>();
static Map<ProcessEngine, String[]> tableNamesCache = new HashMap<ProcessEngine, String[]>();
public static void clean(ProcessEngine processEngine) {
SessionFactory sessionFactory = processEngine.get(SessionFactory.class);
// when running this with a remote ejb invocation configuration, there is no
// session factory and no cleanup needs to be done
if (sessionFactory==null) {
return;
}
String[] cleanSql = cleanSqlCache.get(processEngine);
if (cleanSql == null) {
Configuration configuration = processEngine.get(Configuration.class);
SessionFactoryImplementor sessionFactoryImplementor = (SessionFactoryImplementor) sessionFactory;
Dialect dialect = sessionFactoryImplementor.getDialect();
// loop over all foreign key constraints
List<String> dropForeignKeysSql = new ArrayList<String>();
List<String> createForeignKeysSql = new ArrayList<String>();
Iterator<Table> iter = configuration.getTableMappings();
//if no session-factory is build, the configuration is not fully initialized.
//Hence, the ForeignKey's won't have a referenced table. This is calculated on
//second pass.
configuration.buildMappings();
while (iter.hasNext()) {
Table table = (Table) iter.next();
if (table.isPhysicalTable()) {
String catalog = table.getCatalog();
String schema = table.getSchema();
Iterator<ForeignKey> subIter = table.getForeignKeyIterator();
while (subIter.hasNext()) {
ForeignKey fk = (ForeignKey) subIter.next();
if (fk.isPhysicalConstraint()) {
// collect the drop foreign key constraint sql
dropForeignKeysSql.add(fk.sqlDropString(dialect, catalog, schema));
// MySQLDialect creates an index for each foreign key.
// see
// http://opensource.atlassian.com/projects/hibernate/browse/HHH-2155
// This index should be dropped or an error will be thrown during
// the creation phase
if (dialect instanceof MySQLDialect) {
dropForeignKeysSql.add("alter table " + table.getName() + " drop key " + fk.getName());
}
// and collect the create foreign key constraint sql
createForeignKeysSql.add(fk.sqlCreateString(dialect, sessionFactoryImplementor, catalog, schema));
}
}
}
}
List<String> deleteSql = new ArrayList<String>();
iter = configuration.getTableMappings();
while (iter.hasNext()) {
Table table = (Table) iter.next();
if (table.isPhysicalTable()) {
deleteSql.add("delete from " + table.getName());
}
}
// glue
// - drop foreign key constraints
// - delete contents of all tables
// - create foreign key constraints
// together to form the clean script
List<String> cleanSqlList = new ArrayList<String>();
cleanSqlList.addAll(dropForeignKeysSql);
cleanSqlList.addAll(deleteSql);
cleanSqlList.addAll(createForeignKeysSql);
cleanSql = (String[]) cleanSqlList.toArray(new String[cleanSqlList.size()]);
cleanSqlCache.put(processEngine, cleanSql);
}
Session session = sessionFactory.openSession();
try {
for (String query : cleanSql) {
// log.trace(query);
session.createSQLQuery(query).executeUpdate();
}