hibernate之session管理

原文链接http://zhhll.icu/2020/12/09/%E6%A1%86%E6%9E%B6/hibernate/session%E7%AE%A1%E7%90%86/

session管理

hibernate自身提供了三种管理session的方法

  • session对象的生命周期与本地线程绑定

  • session对象的生命周期与JTA事务绑定

  • hibernate委托程序管理session对象的生命周期

分别对应于hibernate配置文件中hibernate.current_session_context_class属性的三个值

  • thread
  • jta*
  • managed

与线程绑定

在使用session时,使用sessionFactory.getCurrentSession()来获取当前线程的session

在用thread来进行管理时,在进行事务的提交或回滚操作时,session就会关闭

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

注意:在与spring集成时,在使用LocalSessionFactoryBean时会自动的设置该配置,无需在配置文件中进行配置

public LocalSessionFactoryBuilder(DataSource dataSource, ResourceLoader resourceLoader) {
        this.entityTypeFilters = DEFAULT_ENTITY_TYPE_FILTERS;
        this.getProperties().put("hibernate.current_session_context_class", SpringSessionContext.class.getName());
        if (dataSource != null) {
            this.getProperties().put("hibernate.connection.datasource", dataSource);
        }

        this.getProperties().put("hibernate.classLoader.application", resourceLoader.getClassLoader());
        this.resourcePatternResolver = ResourcePatternUtils.getResourcePatternResolver(resourceLoader);
    }

由于本身的博客百度没有收录,博客地址http://zhhll.icu

posted @ 2021-03-16 11:48  拾光师  阅读(104)  评论(0编辑  收藏  举报