hibernate的current_session_context_class配置

64 篇文章 0 订阅
26 篇文章 0 订阅

遇到过的问题:

情景1:

在使用SessionFactory的getCurrentSession方法时遇到如下错误,经过检查,原因如下:

是因为在hibernate.cfg.xml文件中忘记进行了如下设置:

hibernate.current_session_context_class如果是在web容器中运行hibernate,则在hibernate.cfg.xml中加入这句话:

<property name="hibernate.current_session_context_class">jta</property>

如果是在一个单独的需要进行JDBC连接的java application中运行hibernate,则这样设置:

<property name="hibernate.current_session_context_class">thread</property>

解释:

这里getCurrentSession本地事务(本地事务:jdbc)时 要在配置文件里进行如下设置

    * 如果使用的是本地事务(jdbc事务)
 <property name="hibernate.current_session_context_class">thread</property>
 * 如果使用的是全局事务(jta事务)
 <property name="hibernate.current_session_context_class">jta</property> 


 

情景2:

在ssh2中的sessionFactory配置文件中

应将hibernate.current_session_context_class设为org.springframework.orm.hibernate3.SpringSessionContext(默认为此值)

并应用spring管理事务。

如果为<prop key="hibernate.current_session_context_class">thread</prop> 则会报异常,

 

所以还是spring中hibernate.current_session_context_class的问题

在spring的类LocalSessionFactoryBean源码,方法buildSessionFactory中将hibernate.current_session_context_class设为org.springframework.orm.hibernate3.SpringSessionContext

Java代码   收藏代码
  1. if (isExposeTransactionAwareSessionFactory()) {    
  2.    // Set Hibernate 3.1+ CurrentSessionContext implementation,    
  3.    // providing the Spring-managed Session as current Session.    
  4.    // Can be overridden by a custom value for the corresponding Hibernate property.    
  5.    config.setProperty(Environment.CURRENT_SESSION_CONTEXT_CLASS, SpringSessionContext.class.getName());    
  6.    }    
  7.   
  8. if (this.jtaTransactionManager != null) {    
  9.    // Set Spring-provided JTA TransactionManager as Hibernate property.    
  10.    config.setProperty(Environment.TRANSACTION_STRATEGY, JTATransactionFactory.class.getName());    
  11.    config.setProperty(  Environment.TRANSACTION_MANAGER_STRATEGY, LocalTransactionManagerLookup.class.getName());    
  12. }  else {    
  13.    // Makes the Hibernate Session aware of the presence of a Spring-managed transaction.    
  14.    // Also sets connection release mode to ON_CLOSE by default.    
  15.    config.setProperty(Environment.TRANSACTION_STRATEGY, SpringTransactionFactory.class.getName());    
  16.             }    
 

 

知识总结:

hibernate.current_session_context_class属性

sessionFactory.getCurrentSession()可以完成一系列的工作,当调用时hibernate将session绑定到当前线程,事务结束后hibernate将session从当前线程中释放并且关闭session。当再次调用getCurrentSession()时将得到一个新的session,并重新开始这一系列工作。

这样调用方法如下:

Session session = HibernateUtil.getSessionFactory().getCurrentSession();

session.beginTransaction();

Event theEvent = new Event();

theEvent.setTitle(title);

theEvent.setDate(theDate);

session.save(theEvent);

session.getTransaction().commit();   //不需要close session了。 前提是改值设置为了thread.

 

在一个应用程序中,如果DAO 层使用Spring 的hibernate 模板,通过Spring 来控制session 的生命周期,则首选getCurrentSession ()。

使用Hibernate的大多数应用程序需要某种形式的“上下文相关的” session,特定的session在整个特定的上下文范围内始终有效。然而,对不同类型的应用程序而言,要为什么是组成这种“上下文”下一个定义通常 是困难的;不同的上下文对“当前”这个概念定义了不同的范围。在3.0版本之前,使用Hibernate的程序要么采用自行编写的基于 ThreadLocal的上下文session,要么采用HibernateUtil这样的辅助类,要么采用第三方框架(比如Spring或Pico), 它们提供了基于代理(proxy)或者基于拦截器(interception)的上下文相关session。 

 

从3.0.1版本开 始,Hibernate增加了SessionFactory.getCurrentSession()方法。一开始,它假定了采用JTA事务,JTA事务 定义了当前session的范围和上下文(scope and context)。Hibernate开发团队坚信,因为有好几个独立的JTA TransactionManager实现稳定可用,不论是否被部署到一个J2EE容器中,大多数(假若不是所有的)应用程序都应该采用JTA事务管理。 基于这一点,采用JTA的上下文相关session可以满足你一切需要。 

更好的是,从3.1开始,SessionFactory.getCurrentSession()的后台实现是可拔插的。因此,我们引入了新的扩展接口(org.hibernate.context.CurrentSessionContext)和新的配置参数(hibernate.current_session_context_class),以便对什么是“当前session”的范围和上下文(scope and context)的定义进行拔插。

请参阅org.hibernate.context.CurrentSessionContext接口的Javadoc,那里有关于它的契约的详细讨论。它定义了单一的方法,currentSession(),特定的实现用它来负责跟踪当前的上下文session。Hibernate内置了此接口的三种实现。

org.hibernate.context.JTASessionContext - 当前session根据JTA来跟踪和界定。这和以前的仅支持JTA的方法是完全一样的。详情请参阅Javadoc。

org.hibernate.context.ThreadLocalSessionContext - 当前session通过当前执行的线程来跟踪和界定。详情也请参阅Javadoc。

org.hibernate.context.ManagedSessionContext - 当前session通过当前执行的线程来跟踪和界定。但是,你需要负责使用这个类的静态方法将Session实例绑定、或者取消绑定,它并不会打开(open)、flush或者关闭(close)任何Session。

前两种实现都提供了“每数据库事务对应一个session”的编程模型,也称作每次请求一个session。Hibernate session的起始和终结由数据库事务的生存来控制。假若你在纯粹的 Java SE之上采用自行编写代码来管理事务,而不使用JTA,建议你使用Hibernate Transaction API来把底层事务实现从你的代码中隐藏掉。如果你使用JTA,请使用JTA借口来管理Transaction。如果你在支持CMT的EJB容器中执行代码,事务边界是声明式定义的,你不需要在代码中进行任何事务或session管理操作。

hibernate.current_session_context_class配置参数定义了应该采用哪个org.hibernate.context.CurrentSessionContext实现。注意,为了向下兼容,如果未配置此参数,但是存在org.hibernate.transaction.TransactionManagerLookup的配置,Hibernate会采用org.hibernate.context.JTASessionContext。一般而言,此参数的值指明了要使用的实现类的全名,但那三种内置的实现可以使用简写,即"jta"、"thread"和"managed"。

 

1、getCurrentSession()与openSession()的区别?

在 SessionFactory 启动的时候, Hibernate 会根据配置创建相应的 CurrentSessionContext ,在 getCurrentSession() 被调用的时候,实际被执行的方法是CurrentSessionContext.currentSession() 。在 currentSession() 执行时,如果当前 Session 为空,currentSession 会调用SessionFactory的openSession 。所以getCurrentSession() 对于 Java EE 来说是更好的获取 Session 的方法。

* 采用getCurrentSession()创建的session会绑定到当前线程中,而采用openSession()创建的session则不会

* 采用getCurrentSession()创建的session在commit或rollback时会自动关闭,而采用openSession()创建的session必须手动关闭

2、使用getCurrentSession()需要在hibernate.cfg.xml文件中加入如下配置:

* 如果使用的是本地事务(jdbc事务)

<property name="hibernate.current_session_context_class">thread</property>

* 如果使用的是全局事务(jta事务)

<property name="hibernate.current_session_context_class">jta</property>

* 如果使用的是session的管理机制(不太常用)

<property name="hibernate.current_session_context_class">managed</property>

 

利于ThreadLocal模式管理Session

   早在Java1.2推出之时,Java平台中就引入了一个新的支持:java.lang.ThreadLocal,给我们在编写多线程程序

   时提供了一种新的选择。ThreadLocal是什么呢?其实ThreadLocal并非是一个线程的本地实现版本,它并不是一个Thread,

   而是thread local variable(线程局部变量)。也许把它命名为ThreadLocalVar更加合适。线程局部变量(ThreadLocal)

   其实的功用非常简单,就是为每一个使用某变量的线程都提供一个该变量值的副本,是每一个线程都可以独立地改变自己的副本,

   而不会和其它线程的副本冲突。从线程的角度看,就好像每一个线程都完全拥有一个该变量。 

   ThreadLocal是如何做到为每一个线程维护变量的副本的呢?其实实现的思路很简单,在ThreadLocal类中有一个Map,

   用于存储每一个线程的变量的副本。比如下面的示例实现(为了简单,没有考虑集合的泛型): 

public class HibernateUtil {

public static final ThreadLocal session =new ThreadLocal();

public static final SessionFactory sessionFactory;

   static {

      try {

        sessionFactory = new Configuration().configure().buildSessionFactory();

      } catch (Throwable ex) {

           throw new ExceptionInInitializerError(ex);

      }     

}

     public static Session currentSession () throws HibernateException {

        Session s = session.get ();

        if(s == null) {

          s = sessionFactory.openSession ();

          session.set(s);

           }

         return s;

       }

    public static void closeSession() throws HibernateException {

           Session s = session.get ();

        if(s != null) {

            s.close();

        }

        session.set(null);

    }

}

  • 2
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
前言 ............................................................................ xi 1. 教程 ......................................................................... 1 1.1. 第一部分 - 第一个 Hibernate 应用程序 ................................. 1 1.1.1. 设置 ............................................................ 1 1.1.2. 第一个 class ................................................... 3 1.1.3. 映射文件 ........................................................ 4 1.1.4. Hibernate 配置 .................................................. 7 1.1.5. 用 Maven 构建 .................................................. 9 1.1.6. 启动和辅助类 .................................................... 9 1.1.7. 加载并存储对象 ................................................. 10 1.2. 第二部分 - 关联映射 ................................................. 13 1.2.1. 映射 Person 类 ................................................ 13 1.2.2. 单向 Set-based 的关联 ......................................... 14 1.2.3. 使关联工作 ..................................................... 15 1.2.4. 值类型的集合 ................................................... 17 1.2.5. 双向关联 ....................................................... 18 1.2.6. 使双向连起来 ................................................... 19 1.3. 第三部分 - EventManager web 应用程序 ................................. 20 1.3.1. 编写基本的 servlet ............................................. 20 1.3.2. 处理与渲染 ..................................................... 21 1.3.3. 部署与测试 ..................................................... 24 1.4. 总结 ................................................................. 25 2. 体系结构(Architecture) ..................................................... 27 2.1. 概况(Overview) ...................................................... 27 2.2. 实例状态 .............................................................. 29 2.3. JMX 整合 ............................................................. 30 2.4. 对 JCA 的支持 ........................................................ 30 2.5. 上下文相关的会话(Contextual Session) ................................ 30 3. 配置 ........................................................................ 33 3.1. 可编程的配置方式 ...................................................... 33 3.2. 获得 SessionFactory .................................................. 34 3.3. JDBC 连接 ............................................................ 34 3.4. 可选的配置属性 ........................................................ 36 3.4.1. SQL 方言 ...................................................... 42 3.4.2. 外连接抓取(Outer Join Fetching) .............................. 43 3.4.3. 二进制流(Binary Streams) ..................................... 43 3.4.4. 二级缓存与查询缓存 ............................................. 43 3.4.5. 查询语言中的替换 ............................................... 43 3.4.6. Hibernate 的统计(statistics)机制 ............................. 43 3.5. 日志 ................................................................. 44 3.6. 实现 NamingStrategy .................................................. 44 3.7. XML 配置文件 ......................................................... 45 3.8. J2EE 应用程序服务器的集成 ............................................. 46 3.8.1. 事务策略配置 ................................................... 46HIBERNATE - Relational Persis... iv 3.8.2. JNDI 绑定的 SessionFactory ..................................... 47 3.8.3. 在 JTA 环境下使用 Current Session context(当前 session 上下文) 管理 .................................................................. 48 3.8.4. JMX 部署 ...................................................... 48 4. 持久化类(Persistent Classes) .............................................. 51 4.1. 一个简单的 POJO 例子 ................................................. 51 4.1.1. 实现一个默认的(即无参数的)构造方法(constructor) ............. 52 4.1.2. 提供一个标识属性(identifier property)(可选) ................. 52 4.1.3. 使用非final的类(可选) ........................................ 53 4.1.4. 为持久化字段声明访问器(accessors)和是否可变的标志(mutators) (可选) .............................................................. 53 4.2. 实现继承(Inheritance) ............................................... 53 4.3. 实现 equals() 和 hashCode() 方法: ................................... 54 4.4. 动态模型(Dynamic models) ............................................ 55 4.5. 元组片断映射(Tuplizers) ............................................. 57 4.6. EntityNameResolvers ................................................... 58 5. 对象/关系数据库映射基础(Basic O/R Mapping) ................................. 61 5.1. 映射定义(Mapping declaration) ....................................... 61 5.1.1. Doctype ........................................................ 62 5.1.2. Hibernate-mapping .............................................. 63 5.1.3. 类 ............................................................. 64 5.1.4. id ............................................................. 67 5.1.5. 增强的标识符生成器 ............................................. 71 5.1.6. 标识符生成器的优化 ............................................. 72 5.1.7. composite-id ................................................... 72 5.1.8. 鉴别器(discriminator) ........................................ 73 5.1.9. 版本(version)(可选) ........................................ 74 5.1.10. timestamp(可选) .............................................. 75 5.1.11. Property ...................................................... 76 5.1.12. 多对一(many-to-one) ......................................... 78 5.1.13. 一对一 ........................................................ 80 5.1.14. 自然 ID(natural-id) ......................................... 82 5.1.15. 组件(component)和动态组件(dynamic-component) ............... 82 5.1.16. 属性(Properties) ............................................ 83 5.1.17. 子类(subclass) .............................................. 84 5.1.18. 连接的子类(joined-subclass) ................................. 85 5.1.19. 联合子类(union-subclass) .................................... 86 5.1.20. 连接(join) .................................................. 87 5.1.21. Key ........................................................... 88 5.1.22. 字段和规则元素(column and formula elements) ................. 89 5.1.23. 引用(import) ................................................ 90 5.1.24. Any ........................................................... 90 5.2. Hibernate 的类型 ..................................................... 91 5.2.1. 实体(Entities)和值(values) ................................. 91v 5.2.2. 基本值类型 ..................................................... 92 5.2.3. 自定义值类型 ................................................... 93 5.3. 多次映射同一个类 ...................................................... 94 5.4. SQL 中引号包围的标识符 ............................................... 95 5.5. 其他元数据(Metadata) ................................................ 95 5.5.1. 使用 XDoclet 标记 ............................................. 95 5.5.2. 使用 JDK 5.0 的注解(Annotation) .............................. 97 5.6. 数据库生成属性(Generated Properties) ................................ 98 5.7. 字段的读写表达式 ...................................................... 98 5.8. 辅助数据库对象(Auxiliary Database Objects) .......................... 99 6. 集合映射(Collection mappings) ............................................ 101 6.1. 持久化集合类(Persistent collections) ............................... 101 6.2. 集合映射( Collection mappings ) ................................... 102 6.2.1. 集合外键(Collection foreign keys) ........................... 103 6.2.2. 集合元素(Collection elements) ............................... 104 6.2.3. 索引集合类(Indexed collections) ............................. 104 6.2.4. 值集合于多对多关联(Collections of values and many-to-many associations) ....................................................... 105 6.2.5. 一对多关联(One-to-many Associations) ........................ 107 6.3. 高级集合映射(Advanced collection mappings) ......................... 108 6.3.1. 有序集合(Sorted collections) ................................ 108 6.3.2. 双向关联(Bidirectional associations) ........................ 109 6.3.3. 双向关联,涉及有序集合类 ...................................... 111 6.3.4. 三重关联(Ternary associations) .............................. 112 6.3.5. Using an <idbag> ............................................. 112 6.4. 集合例子(Collection example) ....................................... 113 7. 关联关系映射 ............................................................... 117 7.1. 介绍 ................................................................ 117 7.2. 单向关联(Unidirectional associations) .............................. 117 7.2.1. 多对一(many-to-one) ......................................... 117 7.2.2. 一对一(One-to-one) .......................................... 117 7.2.3. 一对多(one-to-many) ......................................... 118 7.3. 使用连接表的单向关联(Unidirectional associations with join tables) .. 119 7.3.1. 一对多(one-to-many) ......................................... 119 7.3.2. 多对一(many-to-one) ......................................... 120 7.3.3. 一对一(One-to-one) .......................................... 120 7.3.4. 多对多(many-to-many) ........................................ 121 7.4. 双向关联(Bidirectional associations) ............................... 122 7.4.1. 一对多(one to many)/多对一(many to one) .................... 122 7.4.2. 一对一(One-to-one) .......................................... 123 7.5. 使用连接表的双向关联(Bidirectional associations with join tables) ... 124 7.5.1. 一对多(one to many)/多对一(many to one) .................... 124 7.5.2. 一对一(one to one) ......................................... 125 7.5.3. 多对多(many-to-many) ........................................ 126HIBERNATE - Relational Persis... vi 7.6. 更复杂的关联映射 ..................................................... 126 8. 组件(Component)映射 ....................................................... 129 8.1. 依赖对象(Dependent objects) ........................................ 129 8.2. 在集合中出现的依赖对象(Collections of dependent objects) ........... 131 8.3. 组件作为 Map 的索引(Components as Map indices ) .................... 132 8.4. 组件作为联合标识符(Components as composite identifiers) ............ 132 8.5. 动态组件(Dynamic components) ....................................... 134 9. 继承映射(Inheritance Mapping) ............................................ 137 9.1. 三种策略 ............................................................. 137 9.1.1. 每个类分层结构一张表(Table per class hierarchy) ............. 137 9.1.2. 每个子类一张表(Table per subclass) .......................... 138 9.1.3. 每个子类一张表(Table per subclass),使用辨别标志 (Discriminator) .................................................... 138 9.1.4. 混合使用“每个类分层结构一张表”和“每个子类一张表” ........... 139 9.1.5. 每个具体类一张表(Table per concrete class) .................. 140 9.1.6. 每个具体类一张表,使用隐式多态 ................................ 141 9.1.7. 隐式多态和其他继承映射混合使用 ................................ 142 9.2. 限制 ................................................................ 142 10. 与对象共事 ................................................................ 145 10.1. Hibernate 对象状态(object states) ................................. 145 10.2. 使对象持久化 ........................................................ 145 10.3. 装载对象 ............................................................ 146 10.4. 查询 ............................................................... 148 10.4.1. 执行查询 ..................................................... 148 10.4.2. 过滤集合 ..................................................... 152 10.4.3. 条件查询(Criteria queries) ................................. 153 10.4.4. 使用原生 SQL 的查询 ......................................... 153 10.5. 修改持久对象 ........................................................ 153 10.6. 修改脱管(Detached)对象 ............................................ 154 10.7. 自动状态检测 ........................................................ 155 10.8. 删除持久对象 ........................................................ 156 10.9. 在两个不同数据库间复制对象 .......................................... 156 10.10. Session 刷出(flush) .............................................. 157 10.11. 传播性持久化(transitive persistence) ............................. 158 10.12. 使用元数据 ......................................................... 160 11. Read-only entities ........................................................ 161 11.1. Making persistent entities read-only ................................ 162 11.1.1. Entities of immutable classes ................................ 162 11.1.2. Loading persistent entities as read-only ..................... 162 11.1.3. Loading read-only entities from an HQL query/criteria ......... 163 11.1.4. Making a persistent entity read-only ......................... 165 11.2. Read-only affect on property type .................................. 166 11.2.1. Simple properties ............................................ 167 11.2.2. Unidirectional associations .................................. 167
F5是一种负载均衡器,可能会对应用程序的Session造成影响。在配置F5时,您需要确保它正确地配置Session保持策略。如果Session保持策略设置不正确,可能会导致Session丢失或过期。 如果您使用的是SSM框架,可以尝试在您的应用程序中添加以下配置: 在web.xml中添加以下配置,启用Session保持: ``` <session-config> <session-timeout>30</session-timeout> // 设置Session过期时间 <cookie-config> <http-only>true</http-only> </cookie-config> </session-config> ``` 在Spring配置文件中添加以下配置,启用Session保持: ``` <bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean"> <property name="dataSource" ref="dataSource"/> <property name="packagesToScan" value="com.example"/> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</prop> <prop key="hibernate.show_sql">true</prop> <prop key="hibernate.format_sql">true</prop> <prop key="hibernate.cache.use_second_level_cache">false</prop> <prop key="hibernate.cache.use_query_cache">false</prop> <prop key="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.SingletonEhCacheRegionFactory</prop> <prop key="hibernate.current_session_context_class">thread</prop> <prop key="hibernate.enable_lazy_load_no_trans">true</prop> <prop key="hibernate.connection.release_mode">on_close</prop> </props> </property> </bean> <bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory"/> </bean> <bean id="sessionInterceptor" class="com.example.SessionInterceptor"> <property name="sessionFactory" ref="sessionFactory"/> </bean> <mvc:interceptors> <mvc:interceptor> <mvc:mapping path="/**"/> <bean class="com.example.SessionInterceptor"/> </mvc:interceptor> </mvc:interceptors> ``` 其中,SessionInterceptor是一个自定义的拦截器,用于处理Session保持。 如果您已经正确配置Session保持策略,但仍然遇到Session过期的问题,您可以考虑增加Session过期时间或者使用Cookie来保存Session。同时,您还可以检查F5的配置是否正确,并确保所有服务器上的应用程序都使用相同的Session保持策略。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值