数据库配置写在Spring配置文件里,因为Spring IOC容器中配置了sessionFactory Bean,它将随应用启动而加载,一旦Dao组件获得sessionFactory bean的引用就可以完成实际数据库访问。如果在应用运行中数据库配置发生改变就需要重新构建seesionFactory实例。
构建sessionFactory方法有三个,仅供参考:
1、重启系统
2、重建sessionfactory
Configuration config=Configuration config=new Configuration().configure();
SessionFactory sessionFactory=config.buildSessionFactory();
3、重建Spring容器
ClassPathXmlApplicationContext ctx = new ClaaPathApplicationContext(newString[]{"WEB-INF/ApplicationContext.xml"})
注意问题,重建sessionFactory需要首先做好释放
/**
* 关闭当前的SessionFactory并且释放所有的资源
*/
public static void shutdown()
{
log.debug("Shutting down Hibernate.");
// Close caches and connection pools
getSessionFactory().close();
// Clear static variables
configuration = null;
sessionFactory = null;
}
/**
* 使用指定的Configuration对象来重新构建SessionFactory对象。
*
* @param cfg
*/
public static void rebuildSessionFactory(Configuration cfg)
{
log.debug("Rebuilding the SessionFactory from given Configuration.");
synchronized(sessionFactory)
{
if (sessionFactory != null && !sessionFactory.isClosed())
sessionFactory.close();
if (cfg.getProperty(Environment.SESSION_FACTORY_NAME) != null)
cfg.buildSessionFactory();
else
sessionFactory = cfg.buildSessionFactory();
configuration = cfg;
}
}
释放Spring 容器:
AbstractApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
// 关闭Spring容器
context.close();
本文介绍了在Spring框架中如何更新数据库配置的方法。当数据库配置发生变化时,可以通过重启系统、重建SessionFactory或重建Spring容器来实现。文章还提供了具体的代码示例说明如何安全地释放资源。
1万+

被折叠的 条评论
为什么被折叠?



