Unit testing Hibernate-based DAOs have an interesting article on Unit Testing Hibernate-based DAOs, that are also implemented using Spring DAO support with the HibernateTemplate.

This article is an excellent checklist of steps needed to Unit Test Hibernate based DAOs. There are a couple of interesting points in the code though will not 100% test your persistence due to the default behavior of Hibernate and it’s caching.

These issues are not addressed until the final point in the article (Step 12: The Session must be flushed) – the author should have mentioned this critical point earlier in the article when showing the code to test persisting a new object and retrieving it. Without the flushing and clearing of the session retrieving an already referenced object by it’s id within the same Session returns the same instance of the object from cache (ie a == b). Although this won’t break the JUnit, unless you had read all the way to the end of the article you might have missed this important point. Without the flushing and clearing of the Session (or using a new Session), the retrieval of the newly persisted object will return a reference to the same object, without actually executing any SQL to retrieve it from the database.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.