1 package org.controlhaus.hibernate; 2 3 import java.io.File; 4 import java.net.URL; 5 6 import net.sf.hibernate.HibernateException; 7 import net.sf.hibernate.SessionFactory; 8 import net.sf.hibernate.cfg.Configuration; 9 10 import org.apache.log4j.Logger; 11 12 /*** 13 * @author <a href="mailto:dan@envoisolutions.com">Dan Diephouse</a> 14 * @since Oct 30, 2004 15 */ 16 public class HibernateFactory 17 { 18 private static Logger logger = Logger.getLogger(HibernateFactory.class.getName()); 19 20 private static HibernateFactory factory = new HibernateFactory(); 21 22 private String location = "/hibernate.cfg.xml"; 23 24 private SessionFactory sessionFactory; 25 26 public SessionFactory getSessionFactory(HibernateControl control) 27 { 28 if ( sessionFactory == null ) 29 { 30 sessionFactory = createSessionFactory(); 31 } 32 33 return sessionFactory; 34 } 35 36 private SessionFactory createSessionFactory() 37 { 38 logger.info( "Initializing Hibernate." ); 39 Configuration hibConfig = new Configuration(); 40 41 try 42 { 43 String mapping = System.getProperty("hibernate.cfg.xml"); 44 if ( mapping == null || mapping.equals("") ) 45 mapping = location; 46 47 logger.debug("Configuration mapping " + mapping); 48 File file = new File( mapping ); 49 50 if ( file.exists() ) 51 hibConfig.configure( file ); 52 else 53 { 54 URL url = getClass().getResource(mapping); 55 if ( url != null ) 56 { 57 hibConfig.configure(url); 58 } 59 else 60 { 61 logger.error("Couldn't find mapping file: " + mapping); 62 throw new RuntimeException("Couldn't find mapping file: " + mapping); 63 } 64 } 65 66 return hibConfig.buildSessionFactory(); 67 } 68 catch (HibernateException e) 69 { 70 logger.error("Mapping problem.", e); 71 throw new RuntimeException( "Mapping problem.", e ); 72 } 73 } 74 75 public static HibernateFactory getInstance() 76 { 77 return factory; 78 } 79 }