Skip to content

Instantly share code, notes, and snippets.

@arockwell
Created May 6, 2009 21:56
Show Gist options
  • Select an option

  • Save arockwell/107772 to your computer and use it in GitHub Desktop.

Select an option

Save arockwell/107772 to your computer and use it in GitHub Desktop.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.util.List;
import javax.persistence.PersistenceException;
import junit.framework.TestCase;
import org.apache.log4j.Logger;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.AnnotationConfiguration;
public abstract class HibernateTestCase extends TestCase {
protected String[] DEFAULT_SCHEMAS = {"SCHEMA1", "SCHEMA2", "SCHEMA3"};
protected static Logger logger = Logger.getLogger(HibernateTestCase.class);
protected SessionFactory sf;
private String configFile = "hypersonic.cfg.xml";
protected void createSchemas(String[] schemas) throws Exception {
Class.forName("org.hsqldb.jdbcDriver");
Connection conn = DriverManager.getConnection("jdbc:hsqldb:.","sa","");
for(String schema: schemas) {
Statement st = conn.createStatement();
String createSchema = "create schema " + schema + " authorization dba";
st.executeUpdate(createSchema);
st.close();
}
conn.close();
}
protected void dropSchemas(String[] schemas) throws Exception {
Class.forName("org.hsqldb.jdbcDriver");
Connection conn = DriverManager.getConnection("jdbc:hsqldb:.","sa","");
for(String schema: schemas) {
Statement st = conn.createStatement();
String dropSchema = "drop schema " + schema;
st.executeUpdate(dropSchema);
st.close();
}
conn.close();
}
protected void setUp() throws Exception {
createSchemas(DEFAULT_SCHEMAS);
Session session = null;
try {
sf = new AnnotationConfiguration().configure(configFile).buildSessionFactory();
session = sf.openSession();
Transaction tx = session.beginTransaction();
insertData(session);
tx.commit();
} catch (Exception e) {
throw new PersistenceException(e);
} finally {
session.close();
}
}
protected abstract void insertData(Session session) throws HibernateException;
protected <T> void doInsertData(List<T> list, Session session) {
for(T t: list) {
session.save(t);
}
}
protected void tearDown() throws Exception {
sf.close();
dropSchemas(DEFAULT_SCHEMAS);
}
public String getConfigFile() {
return configFile;
}
public void setConfigFile(String configFile) {
this.configFile = configFile;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment