View RSS Feed

My Java Tips

Hibernate Session

Rate this Entry
by , 10-31-2011 at 04:44 PM (813 Views)
Declaring your hibernate session as static is not a good idea because a session/connection does not have an endless lifetime.


If you have static hibernate session, change it to dynamic. Everytime you want to run one or more transactions at once, obtain a new session object from sessionfactory. The given code shows
static hibernate session. A new session will be created when getSession() is called for the first time. In the later calls, the same session will be returned.

Java Code:
public class HibernateUtil {

    private static final SessionFactory sessionFactory;
    private static Session  session = null;
    private static Logger logger = Logger.getLogger(HibernateUtil.class.getName());

    static {
        try {

            Configuration conf = new Configuration();
            sessionFactory = conf.configure().buildSessionFactory();

        } catch (Throwable ex) {
            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }

    public static Session getSession() {
        if(session == null){
            try {

                session = sessionFactory.openSession();    

                logger.debug("****************************new session being created**************************************");
                           //sessionFactory.
            } 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);
            }
        }
        return session;
    }
Now I will show how we can make it dynamic.


Review the code below. Its an example Ofcourse, you can put the hibernate code separately.

Java Code:
public Long getNumberMatchingQuery(UnifiedConsumerRecord upr){
		org.hibernate.Query q=null;
		try {
			String query = new String();
			String queryStart = "select count(*) FROM person in CLASS com.ConsumerRecord";

			query += queryStart;

			org.hibernate.SessionFactory sessionFactory;
			org.hibernate.Session session = null;

			Configuration conf = new Configuration();
			sessionFactory = conf.configure().buildSessionFactory();
			session = sessionFactory.openSession();

			q = session.createQuery(query);
		}catch(Throwable ex){
			System.err.println("Initial SessionFactory creation failed." + ex);
			throw new ExceptionInInitializerError(ex);
		}
        return (Long)q.uniqueResult();
    }
Hope this helps.

Submit "Hibernate Session" to Facebook Submit "Hibernate Session" to Digg Submit "Hibernate Session" to del.icio.us Submit "Hibernate Session" to StumbleUpon Submit "Hibernate Session" to Google

Tags: None Add / Edit Tags
Categories
Hibernate

Comments