Search code examples
javahibernatetestingpersistence

what are some common problems with Hibernate/persistence?


I have an application I'd like to test-proof against possible problems related to Hibernate and/or persistence.

What other problems? How do I reproduce them (literally)? And how do you recover from them?

To make it clear: I'm talking about multi-threaded cluster environment (the most complex one).

My one:

org.hibernate.StaleObjectStateException: Row was updated or deleted by another transaction (or unsaved-value mapping was incorrect)

Reproduce:

  • Load the object.
  • UPDATE using HQL.
  • Try to update (save) the loaded object.

Handle: Not sure...


Solution

  • Lazy loading is one the big issues you'll encounter, especially if you follow a standard DAO pattern. You'll end up with lazy loaded collections, but upon coming out of your DAO layer, spring (or something else if you're not using spring) might close the session.

    public class MyDaoImpl implements MyDao {
       @Override
       @Transactional
       public void save(MyObject object) { ... }
    }
    

    In this case, when the call to "save" completes, spring will close your session if you are not within another transaction. As a result, any calls to lazily loaded objects will throw a LazyInitializationException.

    The typical way to handle this is to bind a session to the current thread. In webapps, you can do this easily with the OpenSessionInViewFilter. For command line, you'll probably need to write a utility method which creates a session, binds to the current thread, and then unbinds when you're done. You can find examples of this all over the web.

    And on the subject of collections, if you use the "update" method (again something you'd typically do with a standard DAO pattern), you have to be careful not to replace collection instances, but rather you should manipulate the collection that's already in place. Otherwise, hibernate will have a hard time figuring out what needs to be added/removed/updated.