我在独立应用程序中使用 Hibernate 4.0.1.Final。底层数据库是 MySQL 5.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;
}