获得session的几种方式介绍

获得session的几种方式介绍

1. 怎样获取:

核心思想:通过sessionFactory获得Session

2. 获取方式:

(1)通过hibernate自带的HibernateSessionFactory.java

        SessionFactory sessionFactory = HibernateSessionFactory..getSessionFactory();
        Session session = sessionFactory .getCurrentSession();

(2)通过spring配置sessionFactory
    <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
            <property name="configLocation">
                    <value>classpath:hibernate.cfg.xml</value>
            </property>
    </bean>
a)普通获取:
        ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
        // 从容器 接管Bean

        SessionFactory sessionFactory = (SessionFactory) ac.getBean("sessionFactory");

        Session session = sessionFactory.openSession();


b)通过注解获取:
        @Autowired

        private SessionFactory sessionFactory;

        Session session = sessionFactory.openSession();


猜你喜欢

转载自blog.csdn.net/clk_esunny/article/details/80293640