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();
- }
- }