Keep Hibernate Initializer from Crashing Program

Posted by manyxcxi on Stack Overflow See other posts from Stack Overflow or by manyxcxi
Published on 2010-05-11T19:56:51Z Indexed on 2010/05/11 20:14 UTC
Read the original article Hit count: 290

I have a Java program using a basic Hibernate session factory. I had an issue with a hibernate hbm.xml mapping file and it crashed my program even though I had the getSessionFactory() call in a try catch

                try
                {
                    session = SessionFactoryUtil.getSessionFactory().openStatelessSession();    
                    session.beginTransaction();
                    rh = getRunHistoryEntry(session);
                    if(rh == null)
                    {
                        throw new Exception("No run history information found in the database for run id " + runId_ + "!");
                    }
                }
                catch(Exception ex)
                {
                    logger.error("Error initializing hibernate");
                }

It still manages to break out of this try/catch and crash the main thread. How do I keep it from doing this? The main issue is I have a bunch of cleanup commands that NEED to be run before the main thread shuts down and need to be able to guarantee that even after a failure it still cleans up and goes down somewhat gracefully. The session factory looks like this:

public class SessionFactoryUtil {
    private static final SessionFactory sessionFactory;  

    static {  
        try 
        {  
            // Create the SessionFactory from hibernate.cfg.xml  
            sessionFactory = new Configuration().configure().buildSessionFactory();
        } 
        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() 
    {   try
        {
            return sessionFactory;
        }
        catch(Exception ex)
        {
            return null;
        }
    }  
}

© Stack Overflow or respective owner

Related posts about java

Related posts about hibernate