Databases are sometimes the bane of developer’s lives. Aside from all the fun of managing objects, queries, etc., databases are notorious for occasionally (and non-repeatably) hitting your application with an exception. All sorts of things can cause this:

  • Your connection to the database may be momentarily interrupted. Even “high availability” approaches aren’t proof against this – most of them rely on some form of failover, which means that old connections get broken and new connections have to be established. Unfortunately, your database connection pool is probably holding onto those old connections.
  • In some applications it is possible for two simultaneously-running transactions to deadlock due to issues with the way that locks are obtained. This usually causes the database to reject one of the transactions.
  • There are cases where the design of the application itself might be susceptible to constraint violations. As one example, suppose that you identify users via email addresses, which are supposed to be unique. Before adding someone, you query the database to ensure that the address doesn’t already exist. Because of transaction isolation, however, it may still be possible for two simultaneous attempts to add the same email address to result in a constraint violation exception – if the second attempt’s transaction begins before the first one commits, the second attempt’s “get” will report that the address doesn’t exist.

Having an exception like this cause your application to barf in the user’s face is rarely good design. A much better design is to detect situations in which a repeat attempt is likely to succeed, and to retry the operation. A colleague and I evolved such a framework for Hibernate 3 as part of a series of projects on which we were working. It’s part of a project on SourceForge. It was, however, somewhat over complex because, at the time, we were trying to “hide” Hibernate behind the framework’s facade.

Since we first started on that, the Java Persistence API (JPA) has been nicely standardized. JPA has its advantages – it’s a standard and is supported by JEE servers – and its disadvantages – its query API is, in my opinion, much less readable than Hibernate’s – but it is a standard. Thus, having a similar framework for JPA would be useful. Thus, without further ado, here is a simple one.