Announcement Announcement Module
No announcement yet.
How can I flush the hibernate session in my integration test Page Title Module
Move Remove Collapse
Conversation Detail Module
  • Filter
  • Time
  • Show
Clear All
new posts

  • How can I flush the hibernate session in my integration test

    I have a junit test called testDeleteActivity() which gets the first activity, deletes it, uses jdbcTemplate to query to make sure it was deleted, and then rolls back the transaction.

    public void testDeleteActivity() {
          int numActivities = jdbcTemplate.queryForInt("select count(0) from activities");
          int minId = jdbcTemplate.queryForInt("select min(id) from activities");
          Activity a = activityDao.getActivity(minId);
          int newNumActivities = jdbcTemplate.queryForInt("select count(0) from activities");
          assertEquals(numActivities-1, newNumActivities);
    My junit test class extend the AbstractTransactionalDataSourceSpringContextTests class.

    The test fails when I do the second query, because the session hasn't been flushed yet. I could put a flush() command in my DAO implementation's delete() function... but that seems like a bad idea because every time you delete an activity it will force a flush. The other option is to call flush() in my testDelete function above, but I can't get access to the HibernateTemplate without changing my DAO interface to have a function called getHibernateTemplate or something.

    Is there a good pattern I should use when I want to write a testDelete function and check the results with jdbcTemplate?

  • #2
    You can access the Hibernate Session using SessionFactoryUtils.getSession(SessionFactory sessionFactory, boolean allowCreate)

    The SessionFactory can be obtained by IoC (add public void setSessionFactory(SessionFactory sessionFactory) {...} method).


    • #3
      This was very helpful!

      Thank you!



      • #4
        I often use a HibernateTemplate in my test. Inject the SessionFactory as Tim mentions, but create a HibernateTemplate from it instead of storing the SessionFactory itself. Just like you were implementing a Hibernate DAO but didn't want to extend HibernateDaoSupport.

        This way I can also easily do Hibernate verification in tests, as well as JDBC verification.


        • #5
          Thanks for the tip Rod. I appreciate the suggestion and will give it a try this weekend.