重要!本博文非自愿编写,详见:关于本博客目前情况下,所有内容的声明。
1.在 hibernate.cfg.xml 中添加下述配置
<property name="hibernate.current_session_context_class">thread</property>
2.Util 工具类
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(sessionFactory::openSession); private static final Supplier<Session> sessionSupplier=sessionFactory::getCurrentSession; public static Session getCurrentSession() { //调用Supplier获取返回值。 return sessionSupplier.get(); } public static Session getSession() { //由"ThreadLocal.withInitial"中的Supplier参数确保get返回值必不为空。 return threadLocal.get(); } public static void closeSession() { //由"ThreadLocal.withInitial"中的Supplier参数确保get返回值必不为空。 threadLocal.get().close(); //移除ThreadLocal中的Session,确保下次调用get方法重新调用"ThreadLocal.withInitial"中的Supplier参数。 threadLocal.remove(); } }