开发者

Handling database-related exceptions in Java/Spring

I'm reading the book Spring Recipes right now, and am puzzled by one thing: Any exceptions are thrown as a subclass of Dat开发者_开发知识库aAccessException, 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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜