views:

222

answers:

1

I'm reading the book Spring Recipes right now, and am puzzled by one thing: Any exceptions are thrown as a subclass of DataAccessException, a RuntimeException you're not meant to try/catch.

What I'm worried about is problems that are more likely to happen, especially with inserts. If you're using something like SimpleJdbcTemplate each query is its own transaction, so you can't ensure a key is not in the table then do your insert using getSimpleJdbcTemplare.update(), because the key could have been inserted between the two queries.

Obviously this is something one would want to handle more gracefully than a RuntimeException in a production system. So how do you deal with that?

Thanks.

+2  A: 

a RuntimeException you're not meant to try/catch.

Says who? You don't have to catch RuntimeException, but there's nothing to stop you doing it, it's perfectly acceptable. There is, for example, a subclass of DataAccessException called RecoverableDataAccessException, which is specifically intended to be caught so that a retry can be attempted. There's also OptimisticLockingFailureException, which addresses your next point of transactional clashes due to optimistic locking, and can also be caught and handled specifically by the application.

If you're using something like SimpleJdbcTemplate each query is its own transaction

Not true. If you use Spring's transactional semantics, then SimpleJdbcTemplate (or whatever DAO component you use) will participate in the transaction, with full ACID semantics if the database and transaction manage supports it (which most should). In the case of your example, you can do a select for update (or whatever your database supports) follows by an insert, all within one transaction.

Spring's data access layer is probably its best feature, but it rarely gets the credit for it.

skaffman
Reading further in the book I see you're right about transaction handling. Lots of control, and lots of ways of configuring it. With respect to catching exceptions, I think it's the fault of the book for not just saying "you don't have to", but "but you should, and this is how". Thanks for clearing that up.
dj_segfault