当Hibernate丢失连接时显示消息 [英] Show message when Hibernate losses it's connection
问题描述
我有一个Hibernate J2SE Swing应用程序,我想向用户显示一个MessageBox,指出当互联网连接或网络出现问题时无法建立连接。我知道需要捕获的异常 -
java.sql.SQLRecoverableException:IO错误:网络适配器无法建立连接
但是Hibernate已经在内部处理了这个异常。那么你们建议什么?
你可以实现你自己的 ConnectionProvider 。
基本上,每当Hibernate需要数据库连接时,它都会在其配置的ConnectionProvider上调用 getConnection()。
你可以创建一个子类您正在使用的ConnectionProvider并执行如下操作:
public class MyConnectionProvider extends WhateverConnectionProviderYouAreUsing
{
public Connection getConnection()
{
try
{
return super.getConnection();
}
catch(Exception e)
{
//显示关于连接错误的消息
}
}
在SessionFactory配置中,您必须配置您的自定义ConnectionProvider,如
hibernate.connection.provider_class = your.packagename.MyConnectionProvider
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?
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
这篇关于当Hibernate丢失连接时显示消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!