Erran Morad
Erran Morad

Reputation: 4743

Understanding SessionFactory and Hibernate Sessions

I am learning Hibernate now and I need help to understand how Sessions work. I have some methods in a class which I have given below.

I see there is a getCurrentSession() in SessionFactory class. So, it seems that only one Session can be "active" inside a SessionFactory. Is this SessionFactory like a queue of transactions where the transactions are completed in in order ? If yes, then is it possible to promote a transaction to a higher or lower priority ?

private static SessionFactory factory;  

//Get a hibernate session.
public static Session getSession(){
    if(factory == null){

        Configuration config = HibernateUtil.getConfiguration();
        factory = config.buildSessionFactory();

    }   
    Session hibernateSession = factory.getCurrentSession();
    return hibernateSession;
}

public static void commitTransaction(){
    HibernateUtil.getSession().getTransaction().commit();
}

public static void rollbackTransaction(){       
    HibernateUtil.getSession().getTransaction().rollback();
}

And some more methods that use getTransaction().

Upvotes: 4

Views: 4845

Answers (1)

matt forsythe
matt forsythe

Reputation: 3912

SessionFactory's job is to hide the session creation strategy. For example, in a web application, you probably want the SessionFactory to return create a Session the first time getCurrentSession() is called on a thread, and then return the same Session from that point forward for the duration of the request. (Since you probably want to load customer data from that session, then maybe modify their account in that same session.) Other times, you may want SessionFactory to create a brand new session every time you call getCurrentSession(). So by hiding this decision behind the SessionFactory API, you simply write code that gets the Session from the factory and operates on it.

The Session is what handles transactions. As you probably expect, transactions are started in a Session, and then either complete or rollback. There is really no way to prioritize them since once they are started, you are committed to either rolling it back or committing it.

Upvotes: 6

Related Questions