Chan
Chan

Reputation: 2641

Show message when Hibernate losses it's connection

I have a Hibernate J2SE Swing application and I would like to show user a MessageBox saying that the connection could not be established when the internet connection or the network is having troubles. I know the exception that needs to be caught -

java.sql.SQLRecoverableException: IO Error: The Network Adapter could not establish the connection

But Hibernate has already handled this exception internally. So what do you guys suggest?

Upvotes: 1

Views: 166

Answers (1)

Wolfgang
Wolfgang

Reputation: 3490

You could implmenent your own ConnectionProvider. Basically whenever Hibernate needs a database connection it calls getConnection() on its configured ConnectionProvider.

you could create a subclass of the ConnectionProvider you are currently using and do something like that:

public class MyConnectionProvider extends WhateverConnectionProviderYouAreUsing
  {
      public Connection getConnection()
      {
           try
           {
               return super.getConnection();
           } 
           catch (Exception e)
           {
               // Show message about connection error
           }
       }

In the SessionFactory configuration you have to configure your custom ConnectionProvider like

hibernate.connection.provider_class=your.packagename.MyConnectionProvider 

Upvotes: 3

Related Questions