View Javadoc

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