Search code examples
javahibernatesessionjavafxhql

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


I'm using JavaFX+Hibernate to create a desktop app,however after the user logged in with his/her username, I want the username to be assigned to a global variable similar to PHP $_SESSION variable that can be accessible from anywhere.

this is my code for the 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;
 }

}

Solution

  • Java's equivalent of a "global variable" may be a public accessible static variable. You could create one in your code as

     public class Globals {
         public static String userName;
     }
    

    And the username can be set and read from Globals.userName.

    Note: Using a private field and get and set methods would be more clean....