Hibernate 或 Java 中是否有类似于 PHP $_SESSION 的 Session 变量

is there a Session variable in Hibernate or Java similar to PHP $_SESSION

我正在使用 JavaFX+Hibernate 创建桌面应用程序,但是在用户使用 his/her 用户名 登录后,我希望将用户名分配给类似于 PHP $_SESSION 变量的全局变量,可以从任何地方访问。

这是我的 HibernateUtil.java class

代码
package models;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateUtil {

    private static final SessionFactory sessionFactory = buildSessionFactory();

    public static SessionFactory buildSessionFactory(){

     try{
        // Create the SessionFactory from hibernate.cfg.xml
         System.out.println("creating SessionFactory using HibernateUtil.java");
         SessionFactory f = new Configuration().configure().buildSessionFactory();
         System.out.println("session created successfully");
         return f;
     } catch (Throwable ex){
        // Make sure you log the exception, as it might be swallowed
         System.err.println("Initial SessionFactory creation failed." + ex);
         throw new ExceptionInInitializerError(ex);  

     }

    }

 public static SessionFactory getSessionFactory() {
        return sessionFactory;
 }

}

Java 等同于 "global variable" 可能是 public 可访问的静态变量。您可以在代码中创建一个

 public class Globals {
     public static String userName;
 }

并且可以从 Globals.userName 中设置和读取用户名。

注意:使用 private 字段以及 getset 方法会更干净....

不要使用 "global data"。相反,只需安排将用户名(和其他数据)传递给需要访问它的任何人。 (换句话说,以某种形式使用依赖注入。)

全局数据的(众多)问题之一是您将自己限制为该变量只能有一个值。假设几个月后你的老板来到你的办公室并说了类似 "Our clients love the application you wrote, but many of them have multiple accounts that they want to access at the same time. Can you adapt the app so that they can open multiple tabs and log into each account in a different tab?" 的话。 (这种情况可能不适用于您,但一般原则适用。)如果您已将用户名作为应用程序中的单个全局变量,那么如果不重写任意大部分代码,几乎不可能进行此更改。

参见,例如http://wiki.c2.com/?GlobalVariablesAreBad, https://softwareengineering.stackexchange.com/questions/148108/why-is-global-state-so-evil,以及您可以搜索的许多其他内容,但出于其他原因不这样做。

Hibernate Session跟你想的完全不一样

只要您有桌面应用程序,就必须关心需要在内存中保留什么。您可以创建自己的上下文类型,或者 "Session" 如果您想这样命名并保留您需要的内容。

PHP $_SESSION 的模拟存在于带有 Servlet 的 J2EE Web 应用程序中 API