0

I want to create session factory which is shared by all system database users. As session factory is heavy component it is not right to create it every time user login to application.

My scenario is that, I have an application which is login by system database users i.e. Mysql database users not by application users. So I need a session factory which can be created only once and used by all system database users.

Is it possible to do that?

1 Answer 1

1

Yes, it is possible. you can create a class which have static object of SessionFactory. suppose this class have an static block so that it will execute only once at the time of when the class is loaded into JVM. In that static block you have to initialize SessionFactory and when you want to use sessionFactory you can call getter of sessionFactory object.

public final class SessionFactoryHelper {

    private static SessionFactory sysDBUserSessionFactory;

    static {
        try {
            // initialize  the sysDBUserSessionFactory object.  
        } catch (Exception e) {
            //exception handling
        }
    }

    public static SessionFactory getsysDBUserSessionFactory() {
        return sysDBUserSessionFactory;
    }
}

Whenever you want sessionFactory for system database users use :

SessionFactory sessionFactory = SessionFactoryHelper.getsysDBUserSessionFactory();
Sign up to request clarification or add additional context in comments.

13 Comments

Thanx bro. Let me try your approach.
I have many system database user. So I am confused by which user I build my session factory?
No, building session factory is done at time when class SessionFactoryHelper is loaded into JVM. so you need not to worry when session factory need to be build it's getting build at application load time.
Yes, I know that but, the users login after first user is using the same connection used by first user. Is it possible to create new connection keeping session factory as it is. i.e. not building session factory again but just changing connection username and password which is used by user to login.
I guess no,process of creating instance for Hibernate SessionFactory is an expensive operation but if you have limited system DB users like say (up to 10) then you can maintain static map of <string,SessionFactory> where key part is username and value is it's respective sessionFactory object. But for this approach you have to sure you will not have large number of DB users otherwise application become so heavy to maintain objects only :)
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.