スタンドアロンアプリケーション内でHibernate4.0.1.Finalを使用しています。基盤となるデータベースはMySQL5.5です。JUnit 4.8.1を使用して、データアクセスオブジェクトをテストしています。テストを実行して、JUnitテストが終了したときに、すべての変更がロールバックされるようにします。それを行うためのエレガントな方法はありますか?現在、すべてがコミットされています。これは理にかなっています。これが私のJUnitテストです…</p>
@Before
public void setUp() throws IOException {
final InputStream in = getClass().getClassLoader().getResourceAsStream("test.properties");
testProps = new Properties();
testProps.load(in);
final Configuration configuration = new Configuration();
configuration.configure().setProperty("hibernate.show_sql", "false");
final ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
orgDao = new OrganizationDAOImpl(sessionFactory);
} // setUp
@Test
public void testInsertSchool() {
final Organization org = new Organization();
org.setOrganizationId(testProps.getProperty("test.id"));
org.setName(testProps.getProperty("test.name"));
orgDao.saveOrUpdate(org);
final Organization foundOrg = orgDao.findById(org.getOrganizationId());
Assert.assertEquals(org, foundOrg);
}
これがデータアクセスオブジェクトのコードです…</p>
protected void saveOrUpdate(Object obj) {
try {
startOperation();
session.saveOrUpdate(obj);
tx.commit();
} catch (HibernateException e) {
handleException(e);
} finally {
session.close();
}
}
protected Object find(Class clazz, Serializable id) {
Object obj = null;
try {
startOperation();
obj = session.get(clazz, id);
tx.commit();
} catch (HibernateException e) {
handleException(e);
} finally {
session.close();
}
return obj;
}