hibernate的session是持久化管理器接口,我们用它来从数据库中存取数据。得到Session之前首先要得到sessionFactory。SessionFactory负责一个数据库,也只对应一个XML配置文件(hibernate.cfg.xml),SessionFactory通常只被初始化一次。SessionFactory是线程安全的,很多线程可以同时访问它,获取Session。Session不是线程安全的,它代表与数据库之间的一次操作。Session通过SessionFactory打开,在所有的工作完成后,需要关闭
Session的得到
方式一:
当在Myeclipse8以上的版本引入Myeclipse自带的Hibernate框架后,myeclipse会自动为项目创建一个HibernateSessionFactory类。
代码如下
package com.zhuxuli.HibernateSession;
import javax.persistence.Entity;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.cfg.Configuration;
/**
* Configures and provides access to Hibernate sessions, tied to the
* current thread of execution. Follows the Thread Local Session
* pattern, see {@link http://hibernate.org/42.html }.
*/
@Entity
public class HibernateSessionFactory {
/**
* Location of hibernate.cfg.xml file.
* Location should be on the classpath as Hibernate uses
* #resourceAsStream style lookup for its configuration file.
* The default classpath location of the hibernate config file is
* in the default package. Use #setConfigFile() to update
* the location of the configuration file for