如何理解Hibernate中的HibernateSessionFactory类
package com.zz.util; 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 }.
*/
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 the current session.
*/
private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
private static org.hibernate.SessionFactory sessionFactory; private static Configuration configuration = new Configuration();
private static String CONFIG_FILE_LOCATION = "/hibernate.cfg.xml";
private static String configFile = CONFIG_FILE_LOCATION; static {
try {
configuration.configure(configFile);
sessionFactory = configuration.buildSessionFactory();
} catch (Exception e) {
System.err.println("%%%% Error Creating SessionFactory %%%%");
e.printStackTrace();
}
}
private HibernateSessionFactory() {
} /**
* Returns the ThreadLocal Session instance. Lazy initialize
* the <code>SessionFactory</code> if needed.
*
* @return Session
* @throws HibernateException
*/
public static Session getSession() throws HibernateException {
Session session = (Session) threadLocal.get(); if (session == null || !session.isOpen()) {
if (sessionFactory == null) {
rebuildSessionFactory();
}
session = (sessionFactory != null) ? sessionFactory.openSession()
: null;
threadLocal.set(session);
} return session;
} /**
* Rebuild hibernate session factory
*
*/
public static void rebuildSessionFactory() {
try {
configuration.configure(configFile);
sessionFactory = configuration.buildSessionFactory();
} catch (Exception e) {
System.err.println("%%%% Error Creating SessionFactory %%%%");
e.printStackTrace();
}
} /**
* Close the single hibernate session instance.
*
* @throws HibernateException
*/
public static void closeSession() throws HibernateException {
Session session = (Session) threadLocal.get();
threadLocal.set(null); if (session != null) {
session.close();
}
} /**
* return session factory
*
*/
public static org.hibernate.SessionFactory getSessionFactory() {
return sessionFactory;
} /**
* return session factory
*
* session factory will be rebuilded in the next call
*/
public static void setConfigFile(String configFile) {
HibernateSessionFactory.configFile = configFile;
sessionFactory = null;
}
/**
* return hibernate configuration
*
*/
public static Configuration getConfiguration() {
return configuration;
} }
HibernateSessionFactory类是自定义的SessionFactory,名字可以根据自己的喜好来决定。这里用的是HibernateSessionFactory,其内容及解释。上述代码是由myeclipse 自动生成的;也可以根据自己的情况写出:
package com.zz.util; import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration; //在使用hibernate开发项目,请一定保证只有一个SessionFactory
//一个数据库对应一个SessionFactory 对象.
final public class MySessionFactory { private static SessionFactory sessionFactory=null; private MySessionFactory(){ } static{ sessionFactory =new Configuration().configure("com/zz/config/hsp.cfg.xml").buildSessionFactory();
System.out.println("sessionFactory 类型"+sessionFactory);
} public static SessionFactory getSessionFactory(){
return sessionFactory;
} }
在Hibernate中,Session负责完成对象持久化操作。该文件负责创建Session对象,以及关闭Session对象。从该文件可以看出,Session对象的创建大致需要以下3个步骤:
① 初始化Hibernate配置管理类Configuration。
② 通过Configuration类实例创建Session的工厂类SessionFactory。
③ 通过SessionFactory得到Session实例。
Configuration负责管理Hibernate的配置信息。Hibernate运行时需要一些底层实现的基本信息。这些信息包括:数据库URL、数据库用户名、数据库用户密码、数据库JDBC驱动类、数据库dialect。用于对特定数据库提供支持,其中包含了针对特定数据库特性的实现,如Hibernate数据库类型到特定数据库数据类型的映射等。
使用Hibernate必须首先提供这些基础信息以完成初始化工作,为后续操作做好准备。这些属性在Hibernate配置文件hibernate.cfg.xml中加以设定,当调用:
Configuration config=new Configuration().configure();
时,Hibernate会自动在目录下搜索hibernate.cfg.xml文件,并将其读取到内存中作为后续操作的基础配置。
2. SessionFactory接口
SessionFactory负责创建Session实例,可以通过Configuration实例构建SessionFactory。
Configuration config=new Configuration().configure();
SessionFactorysessionFactory=config.buildSessionFactory();
Configuration实例config会根据当前的数据库配置信息,构造SessionFacory实例并返回。SessionFactory一旦构造完毕,即被赋予特定的配置信息。也就是说,之后config的任何变更将不会影响到已经创建的SessionFactory实例sessionFactory。如果需要使用基于变更后的config实例的SessionFactory,需要从config重新构建一个SessionFactory实例。
SessionFactory保存了对应当前数据库配置的所有映射关系,同时也负责维护当前的二级数据缓存和Statement Pool。由此可见,SessionFactory的创建过程非常复杂、代价高昂。这也意味着,在系统设计中充分考虑到SessionFactory的重用策略。由于SessionFactory采用了线程安全的设计,可由多个线程并发调用。
Session是Hibernate持久化操作的基础,提供了众多持久化方法,如save、update、delete等。通过这些方法,透明地完成对象的增加、删除、修改、查找等操作。
同时,值得注意的是,HibernateSession的设计是非线程安全的,即一个Session实例同时只可由一个线程使用。同一个Session实例的多线程并发调用将导致难以预知的错误。
Session实例由SessionFactory构建:
Configuration config=new Configuration().configure();
SessionFactorysessionFactory=config.buldSessionFactory();
Session session=sessionFactory.openSession();
Transaction是Hibernate中进行事务操作的接口,Transaction接口是对实际事务实现的一个抽象,这些实现包括JDBC的事务、JTA中的UserTransaction,甚至可以是CORBA事务。之所以这样设计是可以让开发者能够使用一个统一的操作界面,使得自己的项目可以在不同的环境和容器之间方便地移值。事务对象通过Session创建。例如以下语句:
Transaction ts=session.beginTransaction();
在Hibernate 2.x中,find()方法用于执行HQL语句。Hibernate 3.x废除了find()方法,取而代之的是Query接口,它们都用于执行HQL语句。Query和HQL是分不开的。
Query query=session.createQuery(“fromtable where id=1”);
例如以下语句:
Query query=session.createQuery("fromtable whereid=?");
就要在后面设置其值:
Query.setString(0,"要设置的值");
上面的方法是通过“?”来设置参数,还可以用“:”后跟变量的方法来设置参数,如上例可以改为:
Query query=session.createQuery("fromtable whereid=:1");
Query.setString("kchValue","要设置的课程号值");
其使用方法是相同的,例如:
Query.setParameter(0,"要设置的值");
Query还有一个list()方法,用于取得一个List集合的示例,此示例中包括可能是一个Object集合,也可能是Object数组集合。例如:
Query query=session.createQuery("fromtable whereid=1");
List list=query.list();
如何理解Hibernate中的HibernateSessionFactory类的更多相关文章
- Hibernate中的Entity类之间的继承关系之一MappedSuperclass
在hibernate中,Entity类可以继承Entity类或非Entity类.但是,关系数据库表之间不存在继承的关系.那么在Entity类之间的继承关系,在数据库表中如何表示呢? Hibernate ...
- [转]深刻理解Python中的元类(metaclass)以及元类实现单例模式
使用元类 深刻理解Python中的元类(metaclass)以及元类实现单例模式 在看一些框架源代码的过程中碰到很多元类的实例,看起来很吃力很晦涩:在看python cookbook中关于元类创建单例 ...
- 深刻理解Python中的元类metaclass(转)
本文由 伯乐在线 - bigship 翻译 英文出处:stackoverflow 译文:http://blog.jobbole.com/21351/ 译注:这是一篇在Stack overflow上很热 ...
- 深刻理解Python中的元类(metaclass)
译注:这是一篇在Stack overflow上很热的帖子.提问者自称已经掌握了有关Python OOP编程中的各种概念,但始终觉得元类(metaclass)难以理解.他知道这肯定和自省有关,但仍然觉得 ...
- [转] 深刻理解Python中的元类(metaclass)
非常详细的一篇深入讲解Python中metaclass的文章,感谢伯乐在线-bigship翻译及作者,转载收藏. 本文由 伯乐在线 - bigship 翻译.未经许可,禁止转载!英文出处:stacko ...
- 深刻理解Python中的元类(metaclass)【转】
译注:这是一篇在Stack overflow上很热的帖子.提问者自称已经掌握了有关Python OOP编程中的各种概念,但始终觉得元类(metaclass)难以理解.他知道这肯定和自省有关,但仍然觉得 ...
- 深刻理解Python中的元类(metaclass)以及元类实现单例模式
在理解元类之前,你需要先掌握Python中的类.Python中类的概念借鉴于Smalltalk,这显得有些奇特.在大多数编程语言中,类就是一组用来描述如何生成一个对象的代码段.在Python中这一点仍 ...
- 深入理解Python中的元类(metaclass)
原文 译注:这是一篇在Stack overflow上很热的帖子.提问者自称已经掌握了有关Python OOP编程中的各种概念,但始终觉得元类(metaclass)难以理解.他知道这肯定和自省有关,但仍 ...
- 深度理解python中的元类
本文转自:(英文版)https://stackoverflow.com/questions/100003/what-is-a-metaclass-in-python (翻译版) http:// ...
随机推荐
- python操作adb代码
adb命令的练习 #!/usr/bin/env python # encoding: utf-8 import os import re nameplt=re.compile("packag ...
- What does “=>” mean in import in scala?(转自StackOverflow问答)
As others have mentioned, it's an import rename. There is however one further feature that proves ...
- Python+Selenium 自动化实现实例-数据驱动实例
#coding=utf-8 from selenium import webdriver driver = webdriver.Firefox() driver.implicitly_wait(10) ...
- CAS单点登陆的两个原理图
最近学习CAS单点登录,所以在网上找了两张比较清晰的原理图以供参考: [CAS浏览器请求认证序列图] 其中:* ST:Service Ticket,用于客户端应用持有,每个ST对应一个用户在一个客户 ...
- TeX中的引号(UVa272)
问题: 在Tex中,做双引号的" `` ",右双引号是" '' "(两个回车左边的).输入一篇包含双引号的文章,你的任务是把它转换成TeX的格式. 样例输入: ...
- Model Binder
上面需检测id是否为null 如果未提供id值或id值类型不匹配,则使用默认值.但仍需校验值是否超出范围
- 常用的gnome shell扩展
usertheme 启用后可自定义shell主题dash-to-dock dock设置unite 将左下角通知栏融入顶部栏(仿unity风格)topicons plus 将左下角通知栏融入顶部栏tas ...
- ASP.NET中登录功能的简单逻辑设计
ASP.NET中登录功能的简单逻辑设计 概述 逻辑设计 ...
- LoadRunner函数–lr_vuser_status_message
http://wenku.baidu.com/link?url=KbKGldKUkam4VyH5Z2doesA0ovQpuwM9nX_SnVMtWjo6rJPxj9DqB51z_m1giMbVo5Db ...
- 【Spark亚太研究院系列丛书】Spark实战高手之路-第2章动手实战Scala第3小节:动手实战Scala函数式编程(2)
3,动手实战Scala中的泛型 泛型泛型类和泛型方法,也就是我们实例化类或者调用方法的时候可以指定其类型,由于Scala的泛型和Java的泛型是一致的,这里不再赘述. 4,动手实战Scala中的隐式转 ...