以前我的项目使用Hibernate+struts架构的,所有的Dao类后台使用的操作数据库都用hibernate,统一使用一个类得到session(就是hibernate实例的工具类,使用静态变量sessionfactory),现在有没有方法给项目增加spring的支持,使这个工具类中的Session交给Spring管理起来? 就是说这个sessionFactory不是静态变量,是由spring注入进来的,所有的Session都是由spring创建的sessionFactory来得到?我得HibernateUtil这个工具类内容如下:
代码 public class HibernateUtil { private static Log log = LogFactory.getLog(HibernateUtil.class); private static final SessionFactory sessionFactory; private static String _configFilePath = "/hibernate.cfg.xml"; static { try { //URL configFileURL = null; URL configFileURL = HibernateUtil.class.getResource(_configFilePath); log.info("lyo get config URL: "+configFileURL); // Create the SessionFactory from hibernate.cfg.xml sessionFactory = new Configuration().configure(configFileURL).buildSessionFactory(); } catch (Throwable ex) { // Make sure you log the exception, as it might be swallowed System.err.println("Initial SessionFactory creation failed." + ex); throw new ExceptionInInitializerError(ex); } } public static SessionFactory getSessionFactory() { return sessionFactory; } public static Session getHibernateCurrentSession(){ return getSessionFactory().getCurrentSession(); } public static void closeSession(){ this.getSessionFactory().getCurrentSession().close(); } }
|
如果用 Spring 来管理起来这个类呢? 我试过用 spring把 sessionFactory注入这个类中,但是总是提示说不能在无事务环境下,使用 session? 有没有做过这种情况的? 请指点!