Example usage for org.hibernate.cfg Configuration configure

List of usage examples for org.hibernate.cfg Configuration configure

Introduction

In this page you can find the example usage for org.hibernate.cfg Configuration configure.

Prototype

@Deprecated
public Configuration configure(org.w3c.dom.Document document) throws HibernateException 

Source Link

Usage

From source file:org.seasar.hibernate3.impl.S2SessionFactoryImpl.java

License:Apache License

public synchronized SessionFactory getSessionFactory() {
    if (sessionFactory_ != null) {
        return sessionFactory_;
    }/*from w  w  w.j  av a  2 s  . c om*/

    Configuration cfg = new Configuration();
    cfg.configure(ResourceUtil.getResource(configPath_));
    if (interceptor_ != null) {
        cfg.setInterceptor(interceptor_);
    }
    sessionFactory_ = cfg.buildSessionFactory();
    return sessionFactory_;
}

From source file:org.smartsnip.persistence.hibernate.DBSessionFactory.java

/**
 * initialize the session factory//from   ww  w. ja va2s  .co  m
 * 
 * @param configFile
 *            the path to the configuration file
 * @throws ExceptionInInitializerError
 */
private static synchronized void initialize(String configFile) throws ExceptionInInitializerError {
    if (configFile == null || configFile.isEmpty()) {
        configFile = "/hibernate.cfg.xml";
    }
    if (factory == null) {
        try {
            Configuration configuration = new Configuration();
            configuration.configure(configFile);

            // add entity classes
            configuration.addAnnotatedClass(DBCategory.class);
            configuration.addAnnotatedClass(DBCode.class);
            configuration.addAnnotatedClass(DBCodeFile.class);
            configuration.addAnnotatedClass(DBComment.class);
            configuration.addAnnotatedClass(DBFavourite.class);
            configuration.addAnnotatedClass(DBLanguage.class);
            configuration.addAnnotatedClass(DBLicense.class);
            configuration.addAnnotatedClass(DBLogin.class);
            configuration.addAnnotatedClass(DBNotification.class);
            configuration.addAnnotatedClass(DBRating.class);
            configuration.addAnnotatedClass(DBSnippet.class);
            configuration.addAnnotatedClass(DBTag.class);
            configuration.addAnnotatedClass(DBUser.class);
            configuration.addAnnotatedClass(DBVote.class);
            configuration.addAnnotatedClass(DBRelTagSnippet.class);

            serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties())
                    .buildServiceRegistry();
            factory = configuration.buildSessionFactory(serviceRegistry);
        } catch (Throwable ex) {
            Logger log = Logger.getLogger(DBSessionFactory.class);
            log.error("Failed to create sessionFactory object.", ex);
            throw new ExceptionInInitializerError(ex);
        }
    }
}

From source file:org.sns.tool.hibernate.dbdd.DatabaseDesignGeneratorTask.java

License:Open Source License

public void execute() throws BuildException {
    if (hibernateConfigClass == null)
        throw new BuildException("hibernateConfigClass was not provided.");

    if (structureRulesClass == null)
        throw new BuildException("structureRulesClass was not provided.");

    if (docBookFile == null)
        throw new BuildException("indexFile was not provided.");

    try {/*from  ww w.  j a  v  a 2s  .  c om*/
        final Configuration configuration = (Configuration) hibernateConfigClass.newInstance();
        if (hibernateConfigFile != null)
            configuration.configure(hibernateConfigFile);

        final TableStructure structure;
        if (structureClass == null) {
            final TableStructureRules rules = (TableStructureRules) structureRulesClass.newInstance();
            structure = new DefaultTableStructure(configuration, rules);
        } else {
            final Constructor ctr = structureClass
                    .getConstructor(new Class[] { Configuration.class, TableStructureRules.class });
            final TableStructureRules rules = (TableStructureRules) structureRulesClass.newInstance();
            structure = (TableStructure) ctr.newInstance(new Object[] { configuration, rules });
        }

        if (dialectClass != null)
            configuration.setProperty(Environment.DIALECT, dialectClass);

        final DatabaseDiagramRenderer ddr = (DatabaseDiagramRenderer) databaseDiagramRendererClass
                .newInstance();
        final MappedClassDocumentationProviders mcdp = (MappedClassDocumentationProviders) mappedClassDocumentationProvidersClass
                .newInstance();

        log("Using Hibernate Configuration " + configuration.getClass());
        log("Using Structure " + structure.getClass());
        log("Using Structure Rules " + structure.getRules().getClass());
        log("Using Dialect " + configuration.getProperty(Environment.DIALECT));
        log("Using Renderer " + ddr.getClass());
        log("Using Mapped Class Documentation Providers " + mcdp.getClass());

        final ByteArrayOutputStream graphvizCmdOutputStreamBuffer = new ByteArrayOutputStream();
        final PrintStream graphvizCmdOutputStream = new PrintStream(graphvizCmdOutputStreamBuffer);

        final DatabaseDesignGeneratorConfig ddgConfig = new DatabaseDesignGeneratorConfig() {
            public File getImagesDirectory() {
                return destDir == null ? docBookFile.getParentFile() : destDir;
            }

            public Configuration getHibernateConfiguration() {
                return configuration;
            }

            public File getDocBookFile() {
                return docBookFile;
            }

            public File getAssociatedJavaDocHome() {
                return associatedJavaDocHome;
            }

            public String getDocumentTitle() {
                return documentTitle == null ? "No documentTitle attribute provided." : documentTitle;
            }

            public TableStructure getTableStructure() {
                return structure;
            }

            public DatabaseDiagramRenderer getDatabaseDiagramRenderer() {
                return ddr;
            }

            public MappedClassDocumentationProviders getMappedClassDocumentationProviders() {
                return mcdp;
            }

            public String getGraphvizDiagramOutputType() {
                return graphvizDotOutputType;
            }

            public String getGraphVizDotCommandSpec() {
                return graphvizDotCmdSpec;
            }

            public PrintStream getGraphVizDotLogOutputStream() {
                return graphvizCmdOutputStream;
            }
        };

        final DatabaseDesignGenerator ddg = new DatabaseDesignGenerator(ddgConfig);
        ddg.generateDatabaseDesign();

        if (logGraphvizOutput)
            log(graphvizCmdOutputStreamBuffer.toString());
    } catch (Exception e) {
        throw new BuildException(e);
    }
}

From source file:org.sns.tool.hibernate.document.diagram.HibernateDiagramGeneratorTask.java

License:Open Source License

public void execute() throws BuildException {
    if (hibernateConfigClass == null)
        throw new BuildException("hibernateConfigClass was not provided.");

    if (diagramFilterClass == null)
        throw new BuildException("diagramFilterClass was not provided.");

    try {/*from   w w w.  ja va 2 s.c  o  m*/
        final HibernateDiagramGeneratorFilter filter = (HibernateDiagramGeneratorFilter) diagramFilterClass
                .newInstance();
        log("Using diagram filter " + filter.getClass());

        final Configuration configuration = (Configuration) hibernateConfigClass.newInstance();
        log("Using configuration " + configuration.getClass());

        if (dialectClass != null) {
            configuration.setProperty(Environment.DIALECT, dialectClass);
            log("Using dialect " + configuration.getProperty(Environment.DIALECT));
        }

        if (hibernateConfigFile != null) {
            configuration.configure(hibernateConfigFile);
            log("Using config file " + hibernateConfigFile);
        }

        final GraphvizDiagramGenerator gdg = new GraphvizDiagramGenerator(diagramId, true,
                GraphvizLayoutType.DOT);
        final HibernateDiagramGenerator hdg = new HibernateDiagramGenerator(configuration, gdg, filter);
        hdg.generate();
        gdg.generateDOTSource(dotFile);

        log("DOT file " + dotFile + " written.");
    } catch (IllegalAccessException e) {
        e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
    } catch (IOException e) {
        e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
    } catch (InstantiationException e) {
        e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
    }
}

From source file:org.socraticgrid.hl7.services.orders.functional.TestHibernate.java

License:Apache License

public static void main(String[] args) {
    // creating configuration object 
    Configuration cfg = new Configuration();
    cfg.configure("hibernate.cfg.xml");//populates the data of the configuration file 
    //creating session factory object 
    SessionFactory factory = cfg.buildSessionFactory();
    //creating session object 
    Session session = factory.openSession();
    //creating transaction object
    Transaction t = session.beginTransaction();
    Quantity quantity = new Quantity();
    quantity.setCode("KG");
    quantity.setUnits("KG");
    quantity.setValue("500");
    session.persist(quantity);/*from   ww w  . j av a2 s  .c  o  m*/
    t.commit();
    session.close();
}

From source file:org.springframework.orm.hibernate3.LocalSessionFactoryBean.java

License:Apache License

@Override
@SuppressWarnings("unchecked")
protected SessionFactory buildSessionFactory() throws Exception {
    // Create Configuration instance.
    Configuration config = newConfiguration();

    DataSource dataSource = getDataSource();
    if (dataSource != null) {
        // Make given DataSource available for SessionFactory configuration.
        configTimeDataSourceHolder.set(dataSource);
    }/*from w  w  w  .j av a 2 s.  c  o  m*/
    if (this.jtaTransactionManager != null) {
        // Make Spring-provided JTA TransactionManager available.
        configTimeTransactionManagerHolder.set(this.jtaTransactionManager);
    }
    if (this.cacheRegionFactory != null) {
        // Make Spring-provided Hibernate RegionFactory available.
        configTimeRegionFactoryHolder.set(this.cacheRegionFactory);
    }
    if (this.lobHandler != null) {
        // Make given LobHandler available for SessionFactory configuration.
        // Do early because because mapping resource might refer to custom types.
        configTimeLobHandlerHolder.set(this.lobHandler);
    }

    // Analogous to Hibernate EntityManager's Ejb3Configuration:
    // Hibernate doesn't allow setting the bean ClassLoader explicitly,
    // so we need to expose it as thread context ClassLoader accordingly.
    Thread currentThread = Thread.currentThread();
    ClassLoader threadContextClassLoader = currentThread.getContextClassLoader();
    boolean overrideClassLoader = (this.beanClassLoader != null
            && !this.beanClassLoader.equals(threadContextClassLoader));
    if (overrideClassLoader) {
        currentThread.setContextClassLoader(this.beanClassLoader);
    }

    try {
        if (isExposeTransactionAwareSessionFactory()) {
            // Set Hibernate 3.1+ CurrentSessionContext implementation,
            // providing the Spring-managed Session as current Session.
            // Can be overridden by a custom value for the corresponding Hibernate property.
            config.setProperty(Environment.CURRENT_SESSION_CONTEXT_CLASS, SpringSessionContext.class.getName());
        }

        if (this.jtaTransactionManager != null) {
            // Set Spring-provided JTA TransactionManager as Hibernate property.
            config.setProperty(Environment.TRANSACTION_STRATEGY, JTATransactionFactory.class.getName());
            config.setProperty(Environment.TRANSACTION_MANAGER_STRATEGY,
                    LocalTransactionManagerLookup.class.getName());
        } else {
            // Makes the Hibernate Session aware of the presence of a Spring-managed transaction.
            // Also sets connection release mode to ON_CLOSE by default.
            config.setProperty(Environment.TRANSACTION_STRATEGY, SpringTransactionFactory.class.getName());
        }

        if (this.entityInterceptor != null) {
            // Set given entity interceptor at SessionFactory level.
            config.setInterceptor(this.entityInterceptor);
        }

        if (this.namingStrategy != null) {
            // Pass given naming strategy to Hibernate Configuration.
            config.setNamingStrategy(this.namingStrategy);
        }

        if (this.typeDefinitions != null) {
            // Register specified Hibernate type definitions.
            Mappings mappings = config.createMappings();
            for (TypeDefinitionBean typeDef : this.typeDefinitions) {
                mappings.addTypeDef(typeDef.getTypeName(), typeDef.getTypeClass(), typeDef.getParameters());
            }
        }

        if (this.filterDefinitions != null) {
            // Register specified Hibernate FilterDefinitions.
            for (FilterDefinition filterDef : this.filterDefinitions) {
                config.addFilterDefinition(filterDef);
            }
        }

        if (this.configLocations != null) {
            for (Resource resource : this.configLocations) {
                // Load Hibernate configuration from given location.
                config.configure(resource.getURL());
            }
        }

        if (this.hibernateProperties != null) {
            // Add given Hibernate properties to Configuration.
            config.addProperties(this.hibernateProperties);
        }

        if (dataSource != null) {
            Class<?> providerClass = LocalDataSourceConnectionProvider.class;
            if (isUseTransactionAwareDataSource() || dataSource instanceof TransactionAwareDataSourceProxy) {
                providerClass = TransactionAwareDataSourceConnectionProvider.class;
            } else if (config.getProperty(Environment.TRANSACTION_MANAGER_STRATEGY) != null) {
                providerClass = LocalJtaDataSourceConnectionProvider.class;
            }
            // Set Spring-provided DataSource as Hibernate ConnectionProvider.
            config.setProperty(Environment.CONNECTION_PROVIDER, providerClass.getName());
        }

        if (this.cacheRegionFactory != null) {
            // Expose Spring-provided Hibernate RegionFactory.
            config.setProperty(Environment.CACHE_REGION_FACTORY, LocalRegionFactoryProxy.class.getName());
        }

        if (this.mappingResources != null) {
            // Register given Hibernate mapping definitions, contained in resource files.
            for (String mapping : this.mappingResources) {
                Resource resource = new ClassPathResource(mapping.trim(), this.beanClassLoader);
                config.addInputStream(resource.getInputStream());
            }
        }

        if (this.mappingLocations != null) {
            // Register given Hibernate mapping definitions, contained in resource files.
            for (Resource resource : this.mappingLocations) {
                config.addInputStream(resource.getInputStream());
            }
        }

        if (this.cacheableMappingLocations != null) {
            // Register given cacheable Hibernate mapping definitions, read from the file system.
            for (Resource resource : this.cacheableMappingLocations) {
                config.addCacheableFile(resource.getFile());
            }
        }

        if (this.mappingJarLocations != null) {
            // Register given Hibernate mapping definitions, contained in jar files.
            for (Resource resource : this.mappingJarLocations) {
                config.addJar(resource.getFile());
            }
        }

        if (this.mappingDirectoryLocations != null) {
            // Register all Hibernate mapping definitions in the given directories.
            for (Resource resource : this.mappingDirectoryLocations) {
                File file = resource.getFile();
                if (!file.isDirectory()) {
                    throw new IllegalArgumentException(
                            "Mapping directory location [" + resource + "] does not denote a directory");
                }
                config.addDirectory(file);
            }
        }

        // Tell Hibernate to eagerly compile the mappings that we registered,
        // for availability of the mapping information in further processing.
        postProcessMappings(config);
        config.buildMappings();

        if (this.entityCacheStrategies != null) {
            // Register cache strategies for mapped entities.
            for (Enumeration<?> classNames = this.entityCacheStrategies.propertyNames(); classNames
                    .hasMoreElements();) {
                String className = (String) classNames.nextElement();
                String[] strategyAndRegion = StringUtils
                        .commaDelimitedListToStringArray(this.entityCacheStrategies.getProperty(className));
                if (strategyAndRegion.length > 1) {
                    config.setCacheConcurrencyStrategy(className, strategyAndRegion[0], strategyAndRegion[1]);
                } else if (strategyAndRegion.length > 0) {
                    config.setCacheConcurrencyStrategy(className, strategyAndRegion[0]);
                }
            }
        }

        if (this.collectionCacheStrategies != null) {
            // Register cache strategies for mapped collections.
            for (Enumeration<?> collRoles = this.collectionCacheStrategies.propertyNames(); collRoles
                    .hasMoreElements();) {
                String collRole = (String) collRoles.nextElement();
                String[] strategyAndRegion = StringUtils
                        .commaDelimitedListToStringArray(this.collectionCacheStrategies.getProperty(collRole));
                if (strategyAndRegion.length > 1) {
                    config.setCollectionCacheConcurrencyStrategy(collRole, strategyAndRegion[0],
                            strategyAndRegion[1]);
                } else if (strategyAndRegion.length > 0) {
                    config.setCollectionCacheConcurrencyStrategy(collRole, strategyAndRegion[0]);
                }
            }
        }

        if (this.eventListeners != null) {
            // Register specified Hibernate event listeners.
            for (Map.Entry<String, Object> entry : this.eventListeners.entrySet()) {
                String listenerType = entry.getKey();
                Object listenerObject = entry.getValue();
                if (listenerObject instanceof Collection) {
                    Collection<Object> listeners = (Collection<Object>) listenerObject;
                    EventListeners listenerRegistry = config.getEventListeners();
                    Object[] listenerArray = (Object[]) Array
                            .newInstance(listenerRegistry.getListenerClassFor(listenerType), listeners.size());
                    listenerArray = listeners.toArray(listenerArray);
                    config.setListeners(listenerType, listenerArray);
                } else {
                    config.setListener(listenerType, listenerObject);
                }
            }
        }

        // Perform custom post-processing in subclasses.
        postProcessConfiguration(config);

        // Build SessionFactory instance.
        logger.info("Building new Hibernate SessionFactory");
        this.configuration = config;
        return newSessionFactory(config);
    }

    finally {
        if (dataSource != null) {
            configTimeDataSourceHolder.remove();
        }
        if (this.jtaTransactionManager != null) {
            configTimeTransactionManagerHolder.remove();
        }
        if (this.cacheRegionFactory != null) {
            configTimeRegionFactoryHolder.remove();
        }
        if (this.lobHandler != null) {
            configTimeLobHandlerHolder.remove();
        }
        if (overrideClassLoader) {
            // Reset original thread context ClassLoader.
            currentThread.setContextClassLoader(threadContextClassLoader);
        }
    }
}

From source file:org.squale.jraf.provider.persistence.hibernate.config.AbstractHibernateConfigReader.java

License:Open Source License

/**
 * Lecture du fichier de configuration a partir d'une URL
 * @param in_url url// www.  j a v a  2 s. co  m
 * @return session factory hibernate
 */
public SessionFactory readConfig(URL in_url, Configuration configutration) {

    SessionFactory sf = null;
    Configuration configuration = new Configuration();
    try {
        sf = configuration.configure(in_url).buildSessionFactory();
    } catch (HibernateException e) {
        String hibernateProblem = "Probleme d'initialisation hibernate.";
        log.fatal(hibernateProblem, e);
        throw new JrafRuntimeException(hibernateProblem, e);
    }
    // depuis JRAF 2.2 : permet d'afficher un message en cas d'exception hibernate speciale:
    // probleme de cache...
    catch (Throwable t) {
        String hibernateProblem = "Probleme d'initialisation hibernate.";
        log.fatal(hibernateProblem, t);
        throw new JrafRuntimeException(hibernateProblem, t);
    }

    return sf;

}

From source file:org.squale.jraf.provider.persistence.hibernate.config.AbstractHibernateConfigReader.java

License:Open Source License

/**
 * Lecture du fichier de configuration a partir d'un fichier
 * @param in_file fichier/*w ww  . j a  v a2  s.c om*/
 * @return session factory hibernate
 */
public SessionFactory readConfig(File in_file, Configuration configuration) {

    SessionFactory sf = null;
    try {
        sf = configuration.configure(in_file).buildSessionFactory();
    } catch (HibernateException e) {
        String hibernateProblem = "Probleme d'initialisation hibernate.";
        log.fatal(hibernateProblem, e);
        throw new JrafRuntimeException(hibernateProblem, e);
    }
    // depuis JRAF 2.2 : permet d'afficher un message en cas d'exception hibernate speciale:
    // probleme de cache...
    catch (Throwable t) {
        String hibernateProblem = "Probleme d'initialisation hibernate.";
        log.fatal(hibernateProblem, t);
        throw new JrafRuntimeException(hibernateProblem, t);
    }
    return sf;
}

From source file:org.transitime.db.hibernate.HibernateUtils.java

License:Open Source License

/**
 * Creates a new session factory. This is to be cached and only access
 * internally since creating one is expensive.
 * /*www  .  java2 s . co  m*/
 * @param dbName
 * @return
 */
private static SessionFactory createSessionFactory(String dbName) throws HibernateException {
    logger.debug("Creating new Hibernate SessionFactory for dbName={}", dbName);

    // Create a Hibernate configuration based on customized config file
    Configuration config = new Configuration();

    // Want to be able to specify a configuration file for now
    // since developing in Eclipse and want all config files
    // to be in same place. But the Config.configure(String) 
    // method can't seem to work with a Windows directory name such
    // as C:/users/Mike/software/hibernate.cfg.xml . Therefore create
    // a File object for that file name and pass in the File object
    // to configure().
    String fileName = DbSetupConfig.getHibernateConfigFileName();
    logger.info("Configuring Hibernate for dbName={} using config file={}", dbName, fileName);
    File f = new File(fileName);
    if (!f.exists()) {
        logger.info(
                "The Hibernate file {} doesn't exist as a regular file " + "so seeing if it is in classpath.",
                fileName);

        // Couldn't find file directly so look in classpath for it
        ClassLoader classLoader = HibernateUtils.class.getClassLoader();
        URL url = classLoader.getResource(fileName);
        if (url != null)
            f = new File(url.getFile());
    }
    if (f.exists())
        config.configure(f);
    else {
        logger.error("Could not load in hibernate config file {}", fileName);
    }

    // Add the annotated classes so that they can be used
    AnnotatedClassesList.addAnnotatedClasses(config);

    // Set the db info for the URL, user name, and password. Use values 
    // from CoreConfig if set. If they are not set then the values will be 
    // obtained from the hibernate.cfg.xml 
    // config file.
    String dbUrl = null;
    if (DbSetupConfig.getDbHost() != null) {
        dbUrl = "jdbc:" + DbSetupConfig.getDbType() + "://" + DbSetupConfig.getDbHost() + "/" + dbName;
        config.setProperty("hibernate.connection.url", dbUrl);
    } else {
        dbUrl = config.getProperty("hibernate.connection.url");
    }

    String dbUserName = DbSetupConfig.getDbUserName();
    if (dbUserName != null) {
        config.setProperty("hibernate.connection.username", dbUserName);
    } else {
        dbUserName = config.getProperty("hibernate.connection.username");
    }

    if (DbSetupConfig.getDbPassword() != null)
        config.setProperty("hibernate.connection.password", DbSetupConfig.getDbPassword());

    // Log info, but don't log password. This can just be debug logging
    // even though it is important because the C3P0 connector logs the info.
    logger.debug(
            "For Hibernate factory project dbName={} " + "using url={} username={}, and configured password",
            dbName, dbUrl, dbUserName);

    // Get the session factory for persistence
    Properties properties = config.getProperties();
    ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(properties).build();
    SessionFactory sessionFactory = config.buildSessionFactory(serviceRegistry);

    // Return the factory
    return sessionFactory;
}

From source file:org.unitime.commons.hibernate.util.HibernateUtil.java

License:Open Source License

public static void configureHibernate(Properties properties) throws Exception {
    if (sSessionFactory != null) {
        sSessionFactory.close();/*from   w  ww.  j a  v  a  2 s.c o  m*/
        sSessionFactory = null;
    }

    if (!NamingManager.hasInitialContextFactoryBuilder())
        NamingManager.setInitialContextFactoryBuilder(new LocalContext(null));

    sLog.info("Connecting to " + getProperty(properties, "connection.url"));
    ClassLoader classLoader = HibernateUtil.class.getClassLoader();
    sLog.debug("  -- class loader retrieved");

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    sLog.debug("  -- document factory created");
    DocumentBuilder builder = factory.newDocumentBuilder();
    builder.setEntityResolver(new EntityResolver() {
        public InputSource resolveEntity(String publicId, String systemId) {
            if (publicId.equals("-//Hibernate/Hibernate Mapping DTD 3.0//EN")) {
                return new InputSource(HibernateUtil.class.getClassLoader()
                        .getResourceAsStream("org/hibernate/hibernate-mapping-3.0.dtd"));
            } else if (publicId.equals("-//Hibernate/Hibernate Mapping DTD//EN")) {
                return new InputSource(HibernateUtil.class.getClassLoader()
                        .getResourceAsStream("org/hibernate/hibernate-mapping-3.0.dtd"));
            } else if (publicId.equals("-//Hibernate/Hibernate Configuration DTD 3.0//EN")) {
                return new InputSource(HibernateUtil.class.getClassLoader()
                        .getResourceAsStream("org/hibernate/hibernate-configuration-3.0.dtd"));
            } else if (publicId.equals("-//Hibernate/Hibernate Configuration DTD//EN")) {
                return new InputSource(HibernateUtil.class.getClassLoader()
                        .getResourceAsStream("org/hibernate/hibernate-configuration-3.0.dtd"));
            }
            return null;
        }
    });
    sLog.debug("  -- document builder created");
    Document document = builder.parse(classLoader.getResource("hibernate.cfg.xml").openStream());
    sLog.debug("  -- hibernate.cfg.xml parsed");

    String dialect = getProperty(properties, "dialect");
    if (dialect != null)
        setProperty(document, "dialect", dialect);

    String idgen = getProperty(properties, "tmtbl.uniqueid.generator");
    if (idgen != null)
        setProperty(document, "tmtbl.uniqueid.generator", idgen);

    if (ApplicationProperty.HibernateClusterEnabled.isFalse())
        setProperty(document, "net.sf.ehcache.configurationResourceName", "ehcache-nocluster.xml");

    // Remove second level cache
    setProperty(document, "hibernate.cache.use_second_level_cache", "false");
    setProperty(document, "hibernate.cache.use_query_cache", "false");
    removeProperty(document, "hibernate.cache.region.factory_class");

    for (Enumeration e = properties.propertyNames(); e.hasMoreElements();) {
        String name = (String) e.nextElement();
        if (name.startsWith("hibernate.") || name.startsWith("connection.")
                || name.startsWith("tmtbl.hibernate.")) {
            String value = properties.getProperty(name);
            if ("NULL".equals(value))
                removeProperty(document, name);
            else
                setProperty(document, name, value);
            if (!name.equals("connection.password"))
                sLog.debug("  -- set " + name + ": " + value);
            else
                sLog.debug("  -- set " + name + ": *****");
        }
    }

    String default_schema = getProperty(properties, "default_schema");
    if (default_schema != null)
        setProperty(document, "default_schema", default_schema);

    sLog.debug("  -- hibernate.cfg.xml altered");

    Configuration cfg = new Configuration();
    sLog.debug("  -- configuration object created");

    cfg.setEntityResolver(new EntityResolver() {
        public InputSource resolveEntity(String publicId, String systemId) {
            if (publicId.equals("-//Hibernate/Hibernate Mapping DTD 3.0//EN")) {
                return new InputSource(HibernateUtil.class.getClassLoader()
                        .getResourceAsStream("org/hibernate/hibernate-mapping-3.0.dtd"));
            } else if (publicId.equals("-//Hibernate/Hibernate Mapping DTD//EN")) {
                return new InputSource(HibernateUtil.class.getClassLoader()
                        .getResourceAsStream("org/hibernate/hibernate-mapping-3.0.dtd"));
            } else if (publicId.equals("-//Hibernate/Hibernate Configuration DTD 3.0//EN")) {
                return new InputSource(HibernateUtil.class.getClassLoader()
                        .getResourceAsStream("org/hibernate/hibernate-configuration-3.0.dtd"));
            } else if (publicId.equals("-//Hibernate/Hibernate Configuration DTD//EN")) {
                return new InputSource(HibernateUtil.class.getClassLoader()
                        .getResourceAsStream("org/hibernate/hibernate-configuration-3.0.dtd"));
            }
            return null;
        }
    });
    sLog.debug("  -- added entity resolver");

    cfg.configure(document);
    sLog.debug("  -- hibernate configured");

    fixSchemaInFormulas(cfg);

    UniqueIdGenerator.configure(cfg);

    (new _BaseRootDAO() {
        void setConf(Configuration cfg) {
            _BaseRootDAO.sConfiguration = cfg;
        }

        protected Class getReferenceClass() {
            return null;
        }
    }).setConf(cfg);
    sLog.debug("  -- configuration set to _BaseRootDAO");

    sSessionFactory = cfg.buildSessionFactory();
    sLog.debug("  -- session factory created");

    (new _BaseRootDAO() {
        void setSF(SessionFactory fact) {
            _BaseRootDAO.sSessionFactory = fact;
        }

        protected Class getReferenceClass() {
            return null;
        }
    }).setSF(sSessionFactory);
    sLog.debug("  -- session factory set to _BaseRootDAO");

    addBitwiseOperationsToDialect();
    sLog.debug("  -- bitwise operation added to the dialect if needed");

    DatabaseUpdate.update();
}