Hibernate的session是怎么创建的

Hibernate的session是怎么创建的,第1张

Hibernat 对数据库的 *** 作是通过Session来实现的,这里的session不同于页面间传递参数的session,

而是类似于JDBC中的 Connection。Session是Hibernate运作的中心,对象的生命周期、事务的管理、数据库的存取都与session息息相关。

  Session是由HibernateSessionFactory创建的,是线程安全的,可以让多个执行线程同时存取 

HibernateSessionFactory而不会有数据共享的问题,但不能让多个线程共享一个Session。

SessionFactory对象的创建:

Java代码

Configuration cfg = new Configuration()configure();

SessionFactory sessions = cfgbuildSessionFactory();

session创建时使用了一个ThreadLocal类来建立一个Session管理的辅助类,使用ThreadLocal可以有效隔离执行所用的数据,

避开了Session的多线程之间的数据共享问题。

//创建一个线程本地变量。

Java代码

public static final ThreadLocal<Session> threadlocal = new ThreadLocal<Session>();

public static orghibernateSessionFactory sessionFactory;

//获取session的方法

public static Sessin getSession() throws HibernateException{

//返回线程局部变量的当前线程的值

Session s = (Session)threadLocalget();

//如果sessionFactory为空,重新创建sessionFactory;如果线程为空,就打开一个新的session

if(session==null || !sessionisOpen()){

if(sessionFactory == null){

rebuildSessionFactory(); session = (sessionFactory != null) sessionFactoryopenSession():null;

// 将hibernate的session放入到线程中保存;只要这个线程不结束,都可以通过线程的get()方法来获取

threadLocalset(session);return session;

你的LiuyanDAO整个类贴上来看看,还有你的session是调用父类的getSession()方法得来的,那么你的父类是什么?LiuyanDAO和其他几个DAO都是继承或实现的一个类或接口吗? 框架上的问题仅看出错的地方有可能看不出来的。

还有,我想父类的getSession()方法中有个sessionFactory的bean吧,通过这个sessionFactory才能得到session,看看你的sessionFactory的类,不过你的其他的Dao都是通过它得来的,估计这里问题不大。

如果使用的是getCurrentSession来创建session的话,在commit后,session就自动被关闭了,也就是不用再sessionclose()了。但是如果使用的是openSession方法创建的session的话,那么必须显示的关闭session,也就是调用sessionclose()方法。

Session对象是通过SessionFactory构建的,下面举个例子来介绍Hibernate两种获取session的方式。

>

public interface Session extends SharedSessionContract,EntityManager,HibernateEntiryManager,AutoCloseable;

主要用于java 应用和hibernate之间运行时的接口;这是一个核心的持久化服务API抽象类概念;

一个session的生命周期主要由逻辑事务管理器的开始和结束界定;

session的主要作用是为映射的实体类实例提供create ,read and delete *** 作;实例可能以下面三种方式的一种状态存在:

transient:从不持久化,不与任何session关联

persistent:与一个唯一性的session关联

detached:前置持久,不与任何session关联

transient实例可能通过调用sav(),persist(),or saveOrUpdate()进行持久化;Persistent实例可能通过transient调用delete();任何实例返回一个由get()或者load()方法返回的持久化对象;Detached实例可能通过update(),saveOrUpdate(),lock() or replicate()进行实例化;在transient or detached状态下的实例也可以通过调用merge()方法,作为一个新的持久化对象进行持久化;

save()和persist()在SQL中执行的结果是INSERT,delete()在SQL中执行的结果是DELETE;update()或merge()在SQL中执行的是UPDATE。持久化实例在写入时间段被发现发生变化,且在SQL中执行了UPDATE。saveOrUpdate()和replicate()执行INSERT或者UPDATE中一种行为;

实现的类并不是线程安全的;因此,每个线程或者事务应该从sessionfactory获取自己的实例;

一个Session实例是序列化的,如果他的持久类是序列化的;

一个典型的事务管理应该使用如下的格式:

Session sess = factoryopenSession();

Transaction tx;

try{

tx = sessbeginTransaction();

//do some work

txcommit();

}catch(Exception e){

if(tx!=null)txrollback();

throw e;

}finally{

sessclose();

}

具体方法如下

All Methods Instance Methods Abstract Methods Deprecated Methods

Modifier and TypeMethod and Description

void addEventListeners ( SessionEventListener  listeners)

Add one or more listeners to the Session

SessionLockRequest buildLockRequest ( LockOptions lockOptions)

Build a LockRequest that specifies the LockMode, pessimistic lock timeout and lock scope

IdentifierLoadAccess byId ( Class  entityClass)

Create an IdentifierLoadAccess instance to retrieve the specified entity by primary key

IdentifierLoadAccess byId ( String entityName)

Create an IdentifierLoadAccess instance to retrieve the specified entity type by primary key

MultiIdentifierLoadAccess byMultipleIds ( Class  entityClass)

Create a MultiIdentifierLoadAccess instance to retrieve multiple entities at once as specified by primary key values

MultiIdentifierLoadAccess byMultipleIds ( String entityName)

Create a MultiIdentifierLoadAccess instance to retrieve multiple entities at once as specified by primary key values

NaturalIdLoadAccess byNaturalId ( Class  entityClass)

Create an NaturalIdLoadAccess instance to retrieve the specified entity by its natural id

NaturalIdLoadAccess byNaturalId ( String entityName)

Create an NaturalIdLoadAccess instance to retrieve the specified entity by its natural id

SimpleNaturalIdLoadAccess bySimpleNaturalId ( Class  entityClass)

Create an SimpleNaturalIdLoadAccess instance to retrieve the specified entity by its simple (single attribute) natural id

SimpleNaturalIdLoadAccess bySimpleNaturalId ( String entityName)

Create an SimpleNaturalIdLoadAccess instance to retrieve the specified entity by its natural id

void cancelQuery ()

Cancel the execution of the current query

void clear ()

Completely clear the session

boolean contains ( String entityName, Object object)

Check if this entity is associated with this Session

Query createFilter ( Object collection, String queryString)

Create a Query instance for the given collection and filter string

Query createNamedQuery ( String name, Class  resultType)

The JPA-defined named, typed query creation method

Query createQuery ( CriteriaDelete deleteQuery)

Query createQuery ( CriteriaQuery  criteriaQuery)

Query createQuery ( CriteriaUpdate updateQuery)

Query createQuery ( String queryString)

Create a Query instance for the given HQL/JPQL query string

Query createQuery ( String queryString, Class  resultType)

Create a typed Query instance for the given HQL/JPQL query string

void delete ( Object object)

Remove a persistent instance from the datastore

void delete ( String entityName, Object object)

Remove a persistent instance from the datastore

void disableFetchProfile ( String name)

Disable a particular fetch profile on this session

void disableFilter ( String filterName)

Disable the named filter for the current session

Connection disconnect ()

Disconnect the session from its underlying JDBC connection

 T doReturningWork ( ReturningWork  work)

Controller for allowing users to perform JDBC related work using the Connection managed by this Session

void doWork ( Work work)

Controller for allowing users to perform JDBC related work using the Connection managed by this Session

void enableFetchProfile ( String name)

Enable a particular fetch profile on this session

Filter enableFilter ( String filterName)

Enable the named filter for this current session

void evict ( Object object)

Remove this instance from the session cache

void flush ()

Force this session to flush

 T get ( Class  entityType, Serializable id)

Return the persistent instance of the given entity class with the given identifier, or null if there is no such persistent instance

 T get ( Class  entityType, Serializable id, LockMode lockMode)

Return the persistent instance of the given entity class with the given identifier, or null if there is no such persistent instance

 T get ( Class  entityType, Serializable id, LockOptions lockOptions)

Return the persistent instance of the given entity class with the given identifier, or null if there is no such persistent instance

Object get ( String entityName, Serializable id)

Return the persistent instance of the given named entity with the given identifier, or null if there is no such persistent instance

Object get ( String entityName, Serializable id, LockMode lockMode)

Return the persistent instance of the given entity class with the given identifier, or null if there is no such persistent instance

Object get ( String entityName, Serializable id, LockOptions lockOptions)

Return the persistent instance of the given entity class with the given identifier, or null if there is no such persistent instance

CacheMode getCacheMode ()

Get the current cache mode

LockMode getCurrentLockMode ( Object object)

Determine the current lock mode of the given object

Filter getEnabledFilter ( String filterName)

Retrieve a currently enabled filter by name

String getEntityName ( Object object)

Return the entity name for a persistent entity

FlushModeType getFlushMode ()

For users of the Hibernate native APIs, we've had to rename this method as defined by Hibernate historically because the JPA contract defines a method of the same name, but returning the JPA FlushModeType rather than Hibernate's FlushMode

FlushMode getHibernateFlushMode ()

Get the current flush mode for this session

Serializable getIdentifier ( Object object)

Return the identifier value of the given entity as associated with this session

LobHelper getLobHelper ()

Retrieve this session's helper/delegate for creating LOB instances

SessionFactory getSessionFactory ()

Get the session factory which created this session

SessionStatistics getStatistics ()

Get the statistics for this session

TypeHelper getTypeHelper ()

Convenience access to the TypeHelper associated with this session's SessionFactory

boolean isDefaultReadOnly ()

Will entities and proxies that are loaded into this session be made read-only by default To determine the read-only/modifiable setting for a particular entity or proxy:

boolean isDirty ()

Does this session contain any changes which must be synchronized with the database In other words, would any DML operations be executed if we flushed this session

boolean isFetchProfileEnabled ( String name)

Is a particular fetch profile enabled on this session

boolean isReadOnly ( Object entityOrProxy)

Is the specified entity or proxy read-only To get the default read-only/modifiable setting used for entities and proxies that are loaded into the session:

 T load ( Class  theClass, Serializable id)

Return the persistent instance of the given entity class with the given identifier, assuming that the instance exists

 T load ( Class  theClass, Serializable id, LockMode lockMode)

Return the persistent instance of the given entity class with the given identifier, obtaining the specified lock mode, assuming the instance exists

 T load ( Class  theClass, Serializable id, LockOptions lockOptions)

Return the persistent instance of the given entity class with the given identifier, obtaining the specified lock mode, assuming the instance exists

void load ( Object object, Serializable id)

Read the persistent state associated with the given identifier into the given transient instance

Object load ( String entityName, Serializable id)

Return the persistent instance of the given entity class with the given identifier, assuming that the instance exists

Object load ( String entityName, Serializable id, LockMode lockMode)

Return the persistent instance of the given entity class with the given identifier, obtaining the specified lock mode, assuming the instance exists

Object load ( String entityName, Serializable id, LockOptions lockOptions)

Return the persistent instance of the given entity class with the given identifier, obtaining the specified lock mode, assuming the instance exists

void lock ( Object object, LockMode lockMode)

Obtain the specified lock level upon the given object

void lock ( String entityName, Object object, LockMode lockMode)

Obtain the specified lock level upon the given object

Object merge ( Object object)

Copy the state of the given object onto the persistent object with the same identifier

Object merge ( String entityName, Object object)

Copy the state of the given object onto the persistent object with the same identifier

void persist ( Object object)

Make a transient instance persistent

void persist ( String entityName, Object object)

Make a transient instance persistent

void reconnect ( Connection connection)

Reconnect to the given JDBC connection

void refresh ( Object object)

Re-read the state of the given instance from the underlying database

void refresh ( Object object, LockMode lockMode)

Re-read the state of the given instance from the underlying database, with the givenLockMode

void refresh ( Object object, LockOptions lockOptions)

Re-read the state of the given instance from the underlying database, with the givenLockMode

void refresh ( String entityName, Object object)

Re-read the state of the given instance from the underlying database

void refresh ( String entityName, Object object, LockOptions lockOptions)

Re-read the state of the given instance from the underlying database, with the givenLockMode

void

ThreadLocal类是一个全局共享Map,里面用于存放每一个线程的唯一实例。

比如你放一个A类进去后,只要还是你这个线程来读取的话,那么这个A类还是你存进去的那个A。

而如果是别的线程来读则是读不到的,因为他的线程号和你是不同滴。

同理,如果你再放一个A类进去就会覆盖你以前存入的A类。

在你的程序中,你首先声明一个final的静态ThreadLocal,是为了让此ThreadLocal成为服务器中唯一的一个实例,然后在这个实例中进行 *** 作:

首先就是查找这个实例中是否存在session,用的是sget()方法,如果你以前存过的话,会给你以前存储过的那个session。相反,如果你没有存过,那么他会将一个null值传递给你程序中的那个sssion。

这时来一个判断,如果是空,那么就将你程序中的session进行初始赋值,并将他放入到ThreadLocal中,以便于下次直接调用。

以上就是关于Hibernate的session是怎么创建的全部的内容,包括:Hibernate的session是怎么创建的、HibernateDaoSupport 中无法获取 session 在线等、利用hibernate 的session得到connnection后,是否需要关闭PreparedStatement、Connection等相关内容解答,如果想了解更多相关内容,可以关注我们,你们的支持是我们更新的动力!

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/9462621.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-04-28
下一篇 2023-04-28

发表评论

登录后才能评论

评论列表(0条)

保存