I'm using Hibernate 4.0.1.Final within a standalone application. The underlying db is MySQL 5.5. Using JUnit 4.8.1, I'm testing my data access object, and would like to run tests so that when my JUnit test ends, all my changes are rolled back. Is there an elegant way to do that? Right now, everything is being committed, which makes sense. Here's my JUnit test …
@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); } Here's the code from the data access object …
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; }