kkiefer
kkiefer

Reputation: 143

How does Spring-JPA EntityManager handle "broken" connections?

I have an application that uses a Spring-EntityManager (JPA) and I wonder what happens if the database happens to be unavailable during the lifetime of my aforesaid application.

I expect in that situation it will throw an exception the first time to do anything on the database, right?

But, say I wait 10 minutes and try again then and the DB happens to be back. Will it recover? Can I arrange it so it does?

Thanks

Upvotes: 2

Views: 1495

Answers (1)

Tomasz Nurkiewicz
Tomasz Nurkiewicz

Reputation: 340963

Actually, neither Spring nor JPA have anything to do with it. Internally all persistence frameworks simply call DataSource.getConnection() and expect to receive (probably pooled) JDBC connection. Once they're done, they close() the connection effectively returning it to the pool.

Now when the DataSource is asked to give a connection but database is unaivalable it will throw an exception. That exception will propagate up and will be somehow handled by whatever framework you use.

Now to answer your question - typically DataSource implementation (like , , etc.) will discard connection known to be broken and replace it with a fresh one. It really depends on the provider, but you can safely assume that once the database is available again, the DataSource will gradually get rid of sick connections and replace them with healthy ones.

Also many DataSource implementors provide ways of testing the connection periodically and before it is returned to the client. This is important in pooled environemnts where the DataSource contains a pool of connections and when the database becomes unavailable it has no way to discover that. So some DataSources test connection (by calling SELECT 1 or similar) before giving it back to the client and do the same once in a while to get rid of broken connections, e.g. due to broken underlying TCP connection.

TL;DR

Yes, you will get an exception and yes the system will work normally once the database is back. BTW you can easily test this!

Upvotes: 7

Related Questions