Configuration、SessionFactory、Session

来源:互联网 发布:淘宝ppc是什么意思 编辑:程序博客网 时间:2024/06/05 16:09

Configuration:

负责管理Hibernate的配置信息,这些配置信息都是从配置文件hibernate.cfg.xml或者Hibernate.properties读取的,当然也可以自定义文件名称,只要在实例化Configuration的时候指定具体的路径就可以了;

org.hibernate.cfg Class Configuration

An instance of Configuration allows(允许)  the application to specify properties and mapping documents to be used when creating a SessionFactory. Usually an application will create a single Configuration, build a single instance of SessionFactory and then instantiate Sessions in threads servicing client requests. The Configuration is meant(意味着) only as an initialization-time object. SessionFactorys are immutable anddo not retain(不保留) anyassociation(关联) back to the Configuration.


A new Configuration will use the properties specified in hibernate.properties by default.


SessionFactiory:

Configuration的实例会根据当前的配置信息,构造SessionFactory实例。SessionFactory是线程安全的,一般情况下一个应用中一个数据库共享一个SessionFactory实例。

 构建SessionFactory
Hibernate的SessionFactory接口提供Session类的实例,Session类用于完成对数据库的操作。由于SessionFactory实例是线程安全
的(而Session实例不是线程安全的),所以每个操作都可以共用同一个SessionFactory来获取Session。

Hibernate配置文件分为两种格式,一种是xml格式的配置文件,另一种是Java属性文件格式的配置文件,因此构建SessionFactory也有两种方法,下面分别介绍。

2.6.1  从XML文件读取配置信息构建SessionFactory
从XML文件读取配置信息构建SessionFactory的具体步骤如下。

(1)创建一个Configuration对象,并通过该对象的configura()方法加载Hibernate配置文件,代码如下。

Configuration config = new Configuration().configure();

configura()方法:用于告诉Hibernate加载hibernate.cfg.xml文件。Configuration在实例化时默认加载classpath中的hibernate.cfg.xml,当然也可以加载名称不是hibernate.cfg.xml的配置文件,例如wghhibernate.cfg.xml,可以通过以下代码实现

Configuration config = new Configuration().configure("wghhibernate.cfg.xml");

(2)完成配置文件和映射文件的加载后,将得到一个包括所有Hibernate运行期参数的Configuration实例,通过Configuration实例的buildSessionFactory()方法可以构建一个惟一的SessionFactory,代码如下。

SessionFactory sessionFactory = config.buildSessionFactory();

构建SessionFactory要放在静态代码块中,因为它只在该类被加载时执行一次。一个典型的构建SessionFactory的代码如下。

  1. import org.hibernate.*;   
  2.   
  3. import org.hibernate.cfg.*;   
  4.   
  5. public class CoreSession {   
  6.   
  7. static SessionFactory sessionFactory;   
  8. //注意到这里的SessionFactory都是static的
  9. //初始化Hibernate,创建SessionFactory实例,只在该类被加载到内存时执行一次   
  10.   
  11. static{   
  12.   
  13.     try{   
  14.   
  15.          Configuration config = new Configuration().configure();   
  16.   
  17.          sessionFactory = config.buildSessionFactory();   
  18.   
  19.     } catch (Exception e) {   
  20.   
  21.         System.out.println(e.getMessage());   
  22.   
  23.     }   
  24.   
  25. }   
  26.   
  27. }   

2.6.2  从Java属性文件读取配置信息构建SessionFactory
从Java属性文件读取配置信息构建SessionFactory的具体步骤如下。

(1)创建一个Configuration对象,此时Hibernate会默认加载classpath中的配置文件hibernate.properties,代码如下。

Configuration config = new Configuration();

(2)由于在配置文件中缺少相应的配置映射文件的信息,所以此处需要通过编码方式加载,这可以通过Configuration对象的

addClass()方法实现,具体代码如下。

config.addClass(BranchForm.class);

addClass()方法用于加载实体类。

(3)完成配置文件和映射文件的加载后,将得到一个包括所有Hibernate运行期参数的Configuration实例,通过Configuration实例

的buildSessionFactory()方法可以构建一个惟一的SessionFactory,代码如下。

SessionFactory sessionFactory = config.buildSessionFactory();

构建SessionFactory要放在静态代码块中,因为它只需在该类被加载时执行一次,一个典型的构建SessionFactory的代码如下。

  1. import org.hibernate.*;   
  2.   
  3. import org.hibernate.cfg.*;   
  4.   
  5. public class CoreSession {   
  6.   
  7. static SessionFactory sessionFactory;   
  8.   
  9. //初始化Hibernate,创建SessionFactory实例,只在该类被加载到内存时执行一次   
  10.   
  11. static{   
  12.   
  13.     try{   
  14.   
  15.        Configuration config = new Configuration();   
  16.   
  17.         config.addClass(BranchForm.class);   
  18.   
  19.         sessionFactory = config.buildSessionFactory();   
  20.   
  21.     } catch (Exception e) {   
  22.   
  23.         System.out.println(e.getMessage());   
  24.   
  25.     }   
  26.   
  27. }   
  28.   
  29. }


Session:

一般的持久化方法(CRUD)都是通过Session来调用的,Session是非线程安全的。

Session的创建与关闭 :Session是一个轻量级对象,通常将每个Session实例和一个数据库事务绑定,也就是每执行一个数据库事务,都应该先创建一个新的Session实例,在使用Session后,还需要关闭Session。

Session的创建

创建SessionFactory后,就可以通过SessionFactory创建Session实例,通过SessionFactory创建Session实例的代码如下。

Session session=sessionFactory.openSession();

创建Session后,就可以通过创建的Session进行持久化操作了。

Session的关闭

在创建Session实例后,不论是否执行事务,最后都需要关闭Session实例,释放Session实例占用的资源。

关闭Session实例的代码如下:session.close();


buildSessionFactory

Instantiate a new SessionFactory, using the properties and mappings in this configuration. The SessionFactory will be immutable, so changes made to the Configuration after building the SessionFactory will notaffect(影响) it.

org.hibernate 
Interface SessionFactory

The main contract here is the creation of Session instances. Usually an application has a single SessionFactory instance and threads servicing client requests obtain(获得,得到) Sessioninstances from this factory.

The internal state of a SessionFactory is immutable. Once(一旦) it is created this internal state isset(设置的). This internal state includes all of themetadata(元数据)about Object/Relational Mapping.

Implementors must be threadsafe.


org.hibernate 
Interface Session

The main runtime interface between a Java application and Hibernate. This is the central API class abstracting the notion(概念) of a persistence(持久化)service.

The lifecycle(生命周期) of a Session is bounded(有界限) by the beginning and end of a logical(逻辑) transaction. (Long transactions might span(跨越,持续,有) several(多个) database transactions.)


The main 
function(功能,用途,函数) of the Session is to offer(提供) create, read and delete operations for instances of mapped entity classes. Instances may exist in one of three states:

transient(短暂的,瞬时的): never 
persistent(持续,持久,固执的), not associated(关联) with any Session
persistent: 
associated with(与..相关) a unique Session
detached(分离的): 
previously(以前) persistent, not associated with any Session

Transient instances may be made persistent by calling save()persist() or saveOrUpdate(). Persistent instances may be made transient by calling delete(). Any instance returned by a get() or load() method is persistent. Detached instances may be made persistent by calling update()saveOrUpdate()lock() or replicate(). The state of a 
transient or detached instance may also be made persistent as a new persistent instance by calling merge().

save() and persist() result in an SQL INSERTdelete() in an SQL DELETE and update() or merge() in an SQL UPDATE. Changes to persistent instances aredetected(检测到) at flush time and also result in an SQL UPDATEsaveOrUpdate() and replicate() result ineither(任何一个) an INSERT or an UPDATE.

It is not intended that implementors be threadsafe. Instead(相反) each thread/transaction shouldobtain(获得,获取) its own instance from a SessionFactory.

Session instance is serializable if its persistent classes are serializable.

typical(典型的) transaction should use the following idiom:

 Session sess = factory.openSession(); Transaction tx; try {     tx = sess.beginTransaction();     //do some work     ...     tx.commit(); } catch (Exception e) {     if (tx!=null) tx.rollback();     throw e; } finally {     sess.close(); } 

If the Session throws an exception, the transaction must be rolled back and the sessiondiscarded(废弃,丢弃). The internal state of the Session might not be consistent(不一致) with the database after the exceptionoccurs(发生).

org.hibernate 
Interface Transaction

Allows the application to defineunits of work(操作单元), whilemaintaining(维护) abstraction from theunderlying(底层的) transaction implementation (eg. JTA, JDBC).

A transaction is 
associated(关联) with a Session and is usually instantiated by a call to Session.beginTransaction(). A single session might span multiple transactions since the notion of a session (a conversation(对话) between the application and the datastore) is of coarser(粗糙) granularity(粒度) than the notion of a transaction. However, it is intended that there be at most one uncommitted Transaction associated with a particular Session at any time.

Implementors are not intended to be threadsafe.

0 0