【发布时间】:2012-12-08 21:23:00
【问题描述】:
我的要求如下:
我需要使用从外部获取的新 HBM 文件频繁地在 Spring Web 应用程序中重新启动(或重建)休眠会话工厂。
目前我的 Sessionfactory 类如下,使用 SessionFactory 代理拦截“OpenSession”调用。
我正在检查重启和重建 sessionFactory 的条件。
我的问题是,在并发环境中,处于其他事务中间的其他用户在重新启动期间受到影响。
是否有办法通过检查所有事务和打开会话来执行重启,并在所有其他完成后执行重建会话工厂?
或存在任何其他解决方案。
代码:
public class DataStoreSessionFactory extends LocalSessionFactoryBean
{
private boolean restartFactory = false;
@Override
protected void postProcessConfiguration(Configuration config) throws HibernateException
{
super.postProcessConfiguration(config);
updateHBMList(config);
}
private void updateHBMList(final Configuration config)
{
config.addXML(modelRegistry.generateMapping());
}
@Override
public SessionFactory getObject()
{
Object obj = super.getObject();
/*
* Invocation handler for the proxy
*/
SessionFactoryProxy proxy = new SessionFactoryProxy(this, (SessionFactory) obj);
/**
* All the methods invoked on the returned session factory object will pass through this proxy's invocation
* handler
*/
SessionFactory sessionFactory = (SessionFactory) Proxy.newProxyInstance(getClass().getClassLoader(),
new Class[] { SessionFactory.class },
proxy);
return sessionFactory;
}
static class SessionFactoryProxy implements InvocationHandler
{
private SessionFactory sessionFactory;
private LocalSessionFactoryBean factoryBean;
public SessionFactoryProxy(LocalSessionFactoryBean factoryBean, SessionFactory sessionFactory)
{
this.factoryBean = factoryBean;
this.sessionFactory = sessionFactory;
}
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable
{
/**
* Only if the method invoked is openSession - check if the session factory should be restarted, and only then
* invoke the requested method
*/
if (method.getName().equals("openSession"))
{
restartSessionFactoryIfNecessary();
}
return method.invoke(sessionFactory, args);
}
private void restartSessionFactoryIfNecessary()
{
restartSessionFactory();
/*if (((DataStoreSessionFactory) factoryBean).isRestartFactory())
{
restartSessionFactory();
}*/
}
private synchronized void restartSessionFactory()
{
log.info("Restarting session...");
factoryBean.destroy();
try
{
factoryBean.afterPropertiesSet();
sessionFactory = factoryBean.getObject();
}
catch (Exception e)
{
log.error("Error while restarting session: " + e.getMessage());
throw new RuntimeException(e);
}
}
}
谢谢, 阿帕萨米
【问题讨论】:
-
为什么不在办公时间重建会话工厂?
-
哎呀,你的应用程序必须有一些讨厌的设计/架构。在运行时更改休眠/数据库配置并不好......
标签: java spring hibernate sessionfactory