工具类:session的单例工厂方法

hibernate.cfg.xml

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

Util.java

import java.util.function.*;
import org.hibernate.*;
import org.hibernate.cfg.*;

public class Util {
	private static final SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
	private static final ThreadLocal<Session> threadLocal = ThreadLocal.withInitial(new Supplier<Session>() {

		public Session get() {
			return sessionFactory.openSession();
		}
	});

	public static Session getCurrentSession() {
		return sessionFactory.getCurrentSession();
	}

	public static Session getSession() {
		return threadLocal.get();
	}

	public static void closeSession() {
		threadLocal.get().close();
		threadLocal.remove();
	}
}

展开阅读全文

没有更多推荐了,返回首页