创建SessionTest.java
package com.Entity;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class SessionTest {
private static SessionFactory factory;
private static ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
// 获取SessionFactory
static { // 静态初始化块,加载配置信息
Configuration cfg = new Configuration().configure(); // 读取hibernate.cfg.xml文件
factory = cfg.buildSessionFactory(); // 建立SessionFactory
}
public static Session getSession() {
Session session = threadLocal.get(); //获取当前线程下的session
if(session==null) {
System.out.println("session is null!");
session = factory.openSession();
threadLocal.set(session);
}
return session;
}
public static void closeSession() {
Session session = threadLocal.get();
//如果session不为null,则关闭session,并清空ThreadLocal
if(session!=null) {
session.close();
threadLocal.set(null);
}
}
}
创建Threads.java
package com.Entity;
import org.hibernate.Session;
import com.Entity.SessionTest;
public class Threads extends Thread{
@Override
public void run() {
Session session1 = SessionTest.getSession();
Session session2 = SessionTest.getSession();
Session session3 = SessionTest.getSession();
long threadId = this.getId(); //获取线程id
//输出hashCode,分辨是否是同一个session实例
System.out.println("线程" +threadId+ ":\n" + session1.hashCode() + "\n" + session2.hashCode() + "\n" + session3.hashCode());
}
}
最后做测试Test.java
package com.DAO;
import com.Entity.Threads;
public class Test {
public static void main(String[] args) {
Threads thread1 = new Threads();
Threads thread2 = new Threads();
Threads thread3 = new Threads();
//启动线程
thread1.start();
thread2.start();
thread3.start();
}
}
运行结果截图: