---
title: "Hibernate part 16：管理Session与ThreadLocal绑定"
author: "mvplee"
date: "2015-08-31T14:02:09Z"
tags: []
categories: ["企业架构"]
slug: "hibernate-part-16-session-threadlocal"
draft: false
lastmod: "2015-08-31T14:02:09Z"
id: 2239533
url: "https://mvplee.iteye.com/blog/2239533"
---

hibernate.cfg.xml中的配置

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

 层序中获取通过SessionFactory获取session时使用getCurrentSession()

```
	@Test
	public void test01() {
		Session s1 = HibernateUtils.openSession();
		Session s2 = HibernateUtils.openSession();
		System.out.println(s1 == s2);//false
		Session s3 = HibernateUtils.getCurrentSession();
		Session s4 = HibernateUtils.getCurrentSession();
		System.out.println(s3 == s4);//true
	}
```

 与当前线程绑定的Session会自动关闭， 当Transaction 提交后，Session 会自动关闭

```
@Test
	public void test02() {
		Session session = HibernateUtils.getCurrentSession();
		Transaction transaction = session.beginTransaction();

		session.get(Customer.class, 1);
		
		transaction.commit();
                //不需要手动关闭，org.hibernate.SessionException: Session was already closed
		session.close();
	}
```