Example usage for org.hibernate.cfg Configuration addXML

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

Introduction

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

Prototype

@Deprecated
public Configuration addXML(String xml) throws MappingException 

Source Link

Usage

From source file:com.xpn.xwiki.store.XWikiHibernateStore.java

License:Open Source License

public boolean injectCustomMapping(BaseClass doc1class, XWikiContext context) throws XWikiException {
    // If we haven't turned of dynamic custom mappings we should not inject them
    if (context.getWiki().hasDynamicCustomMappings() == false) {
        return false;
    }/*from  w ww  .j  a v a 2  s  .c o  m*/

    String custommapping = doc1class.getCustomMapping();
    if (!doc1class.hasExternalCustomMapping()) {
        return false;
    }

    Configuration config = getConfiguration();

    // don't add a mapping that's already there
    if (config.getClassMapping(doc1class.getName()) != null) {
        return true;
    }

    Configuration mapconfig = makeMapping(doc1class.getName(), custommapping);
    if (!isValidCustomMapping(doc1class.getName(), mapconfig, doc1class)) {
        throw new XWikiException(XWikiException.MODULE_XWIKI_STORE,
                XWikiException.ERROR_XWIKI_STORE_HIBERNATE_INVALID_MAPPING, "Invalid Custom Mapping");
    }

    config.addXML(makeMapping(doc1class.getName(), "xwikicustom_" + doc1class.getName().replaceAll("\\.", "_"),
            custommapping));
    config.buildMappings();
    return true;
}

From source file:lucee.runtime.orm.hibernate.HibernateSessionFactory.java

License:Open Source License

public static Configuration createConfiguration(Log log, String mappings, DatasourceConnection dc,
        SessionFactoryData data) throws SQLException, IOException, PageException {
    /*/* w ww  .j  a  v a2 s.c  o m*/
     autogenmap
     cacheconfig
     cacheprovider
     cfclocation
     datasource
     dbcreate
     eventHandling
     flushatrequestend
     ormconfig
     sqlscript
     useDBForMapping
     */

    ORMConfiguration ormConf = data.getORMConfiguration();

    // dialect
    DataSource ds = dc.getDatasource();
    String dialect = null;
    try {
        if (Class.forName(ormConf.getDialect()) != null) {
            dialect = ormConf.getDialect();
        }
    } catch (Exception e) {
        // MZ: The dialect value could not be bound to a classname or instantiation causes an exception - ignore and use the default dialect entries
    }
    if (dialect == null) {
        dialect = Dialect.getDialect(ormConf.getDialect());
        if (Util.isEmpty(dialect))
            dialect = Dialect.getDialect(ds);
    }
    if (Util.isEmpty(dialect))
        throw ExceptionUtil.createException(data, null,
                "A valid dialect definition inside the " + Constants.APP_CFC + "/" + Constants.CFAPP_NAME
                        + " is missing. The dialect cannot be determinated automatically",
                null);

    // Cache Provider
    String cacheProvider = ormConf.getCacheProvider();
    Class<? extends RegionFactory> regionFactory = null;

    if (Util.isEmpty(cacheProvider) || "EHCache".equalsIgnoreCase(cacheProvider)) {
        regionFactory = net.sf.ehcache.hibernate.EhCacheRegionFactory.class;
        cacheProvider = regionFactory.getName();//"org.hibernate.cache.EhCacheProvider";

    } else if ("JBossCache".equalsIgnoreCase(cacheProvider))
        cacheProvider = "org.hibernate.cache.TreeCacheProvider";
    else if ("HashTable".equalsIgnoreCase(cacheProvider))
        cacheProvider = "org.hibernate.cache.HashtableCacheProvider";
    else if ("SwarmCache".equalsIgnoreCase(cacheProvider))
        cacheProvider = "org.hibernate.cache.SwarmCacheProvider";
    else if ("OSCache".equalsIgnoreCase(cacheProvider))
        cacheProvider = "org.hibernate.cache.OSCacheProvider";

    Resource cacheConfig = ormConf.getCacheConfig();
    Configuration configuration = new Configuration();

    // ormConfig
    Resource conf = ormConf.getOrmConfig();
    if (conf != null) {
        try {
            Document doc = CommonUtil.toDocument(conf, null);
            configuration.configure(doc);
        } catch (Throwable t) {
            LogUtil.log(log, Log.LEVEL_ERROR, "hibernate", t);

        }
    }

    try {
        configuration.addXML(mappings);
    } catch (MappingException me) {
        throw ExceptionUtil.createException(data, null, me);
    }

    configuration

            // Database connection settings
            .setProperty("hibernate.connection.driver_class", ds.getClazz().getName())
            .setProperty("hibernate.connection.url", ds.getDsnTranslated());
    if (!StringUtil.isEmpty(ds.getUsername())) {
        configuration.setProperty("hibernate.connection.username", ds.getUsername());
        if (!StringUtil.isEmpty(ds.getPassword()))
            configuration.setProperty("hibernate.connection.password", ds.getPassword());
    }
    //.setProperty("hibernate.connection.release_mode", "after_transaction")
    configuration.setProperty("hibernate.transaction.flush_before_completion", "false")
            .setProperty("hibernate.transaction.auto_close_session", "false")

            // JDBC connection pool (use the built-in)
            //.setProperty("hibernate.connection.pool_size", "2")//MUST

            // SQL dialect
            .setProperty("hibernate.dialect", dialect)
            // Enable Hibernate's current session context
            .setProperty("hibernate.current_session_context_class", "thread")

            // Echo all executed SQL to stdout
            .setProperty("hibernate.show_sql", CommonUtil.toString(ormConf.logSQL()))
            .setProperty("hibernate.format_sql", CommonUtil.toString(ormConf.logSQL()))
            // Specifies whether secondary caching should be enabled
            .setProperty("hibernate.cache.use_second_level_cache",
                    CommonUtil.toString(ormConf.secondaryCacheEnabled()))
            // Drop and re-create the database schema on startup
            .setProperty("hibernate.exposeTransactionAwareSessionFactory", "false")
            //.setProperty("hibernate.hbm2ddl.auto", "create")
            .setProperty("hibernate.default_entity_mode", "dynamic-map");

    if (!Util.isEmpty(ormConf.getCatalog()))
        configuration.setProperty("hibernate.default_catalog", ormConf.getCatalog());
    if (!Util.isEmpty(ormConf.getSchema()))
        configuration.setProperty("hibernate.default_schema", ormConf.getSchema());

    if (ormConf.secondaryCacheEnabled()) {
        if (cacheConfig != null && cacheConfig.isFile())
            configuration.setProperty("hibernate.cache.provider_configuration_file_resource_path",
                    cacheConfig.getAbsolutePath());
        if (regionFactory != null || Reflector.isInstaneOf(cacheProvider, RegionFactory.class))
            configuration.setProperty("hibernate.cache.region.factory_class", cacheProvider);
        else
            configuration.setProperty("hibernate.cache.provider_class", cacheProvider);

        configuration.setProperty("hibernate.cache.use_query_cache", "true");

        //hibernate.cache.provider_class=org.hibernate.cache.EhCacheProvider
    }

    /*
    <!ELEMENT tuplizer EMPTY> 
     <!ATTLIST tuplizer entity-mode (pojo|dom4j|dynamic-map) #IMPLIED>   <!-- entity mode for which tuplizer is in effect --> 
     <!ATTLIST tuplizer class CDATA #REQUIRED>                           <!-- the tuplizer class to use --> 
    */

    schemaExport(log, configuration, dc, data);

    return configuration;
}

From source file:org.eclipse.emf.cdo.server.internal.hibernate.HibernateStore.java

License:Open Source License

protected void initDataStore() {
    if (TRACER.isEnabled()) {
        TRACER.trace("Initializing Configuration"); //$NON-NLS-1$
    }/*from w ww.  ja v a  2s. c  o  m*/

    InputStream in = null;

    try {
        PackageRegistryProvider.getInstance().setThreadPackageRegistry(getRepository().getPackageRegistry());

        cdoDataStore = new CDODataStore();
        hibernateAuditHandler = new HibernateAuditHandler();
        hibernateAuditHandler.setCdoDataStore(cdoDataStore);
        hibernateAuditHandler.setHibernateStore(this);

        cdoDataStore.setResetConfigurationOnInitialization(false);
        cdoDataStore.setName("cdo");
        cdoDataStore.setPackageRegistry(getRepository().getPackageRegistry());
        cdoDataStore.getExtensionManager().registerExtension(EMFInterceptor.class.getName(),
                CDOInterceptor.class.getName());
        cdoDataStore.getExtensionManager().registerExtension(AuditHandler.class.getName(),
                CDOAuditHandler.class.getName());
        cdoDataStore.getExtensionManager().registerExtension(AuditProcessHandler.class.getName(),
                CDOAuditProcessHandler.class.getName());

        // don't do any persistence xml mapping in this datastore
        // make a local copy as it is adapted in the next if-statement
        // and we want to keep the original one untouched, if not
        // subsequent test runs will fail as they use the same
        // properties object
        final Properties props = new Properties();
        props.putAll(getProperties());
        props.remove(PersistenceOptions.PERSISTENCE_XML);

        if (!props.containsKey(PersistenceOptions.HANDLE_UNSET_AS_NULL)) {
            props.setProperty(PersistenceOptions.HANDLE_UNSET_AS_NULL, "true");
        }

        cdoDataStore.setDataStoreProperties(props);
        Configuration hibernateConfiguration = cdoDataStore.getConfiguration();

        if (mappingProvider != null) {
            mappingProvider.setHibernateStore(this);
            mappingXml = mappingProvider.getMapping();
            hibernateConfiguration.addXML(mappingXml);
        }

        if (TRACER.isEnabled()) {
            TRACER.trace("Adding resource.hbm.xml to configuration"); //$NON-NLS-1$
        }

        in = OM.BUNDLE.getInputStream(RESOURCE_HBM_PATH);
        hibernateConfiguration.addInputStream(in);
        // hibernateConfiguration.setInterceptor(new CDOInterceptor());

        hibernateConfiguration.setProperties(props);

        // prevent the drop on close because the sessionfactory is also closed when
        // new packages are written to the db, so only do a real drop at deactivate
        if (hibernateConfiguration.getProperty(Environment.HBM2DDL_AUTO) != null
                && hibernateConfiguration.getProperty(Environment.HBM2DDL_AUTO).startsWith(HBM2DLL_CREATE)) {
            doDropSchema = true;
            // note that the value create also re-creates the db and drops the old one
            hibernateConfiguration.setProperty(Environment.HBM2DDL_AUTO, HBM2DLL_UPDATE);
            cdoDataStore.getDataStoreProperties().setProperty(Environment.HBM2DDL_AUTO, HBM2DLL_UPDATE);
        } else {
            doDropSchema = false;
        }

        final List<EPackage> ePackages = new ArrayList<EPackage>(packageHandler.getEPackages());

        // get rid of the system packages
        for (EPackage ePackage : packageHandler.getEPackages()) {
            if (CDOModelUtil.isSystemPackage(ePackage) && ePackage != EtypesPackage.eINSTANCE) {
                ePackages.remove(ePackage);
            }
        }
        // remove the persistence xml if no epackages as this won't work without
        // epackages
        if (ePackages.size() == 0 && props.getProperty(PersistenceOptions.PERSISTENCE_XML) != null) {
            cdoDataStore.getDataStoreProperties().remove(PersistenceOptions.PERSISTENCE_XML);
        }

        if (isAuditing()) {
            auditEPackages = createAuditEPackages(cdoDataStore);
            final String auditMapping = mapAuditingEPackages(cdoDataStore, auditEPackages);
            // System.err.println(auditMapping);
            hibernateConfiguration.addXML(auditMapping);
            cdoDataStore.setAuditing(true);
        }
        cdoDataStore.setEPackages(ePackages.toArray(new EPackage[0]));
    } catch (Exception ex) {
        throw WrappedException.wrap(ex);
    } finally {
        PackageRegistryProvider.getInstance().setThreadPackageRegistry(null);
        IOUtil.close(in);
    }
}

From source file:org.geolatte.common.automapper.AutoMapperTest.java

License:Open Source License

private SessionFactory buildSessionFactory(Document mapping) {
    Configuration config = new Configuration().configure();
    config.addXML(mapping.asXML());
    return config.buildSessionFactory();
}

From source file:org.geolatte.featureserver.dbase.DbaseFacade.java

License:Open Source License

/**
 * Private constructor of the database facade. Maps all tables currently present in the database!
 *
 * @throws java.sql.SQLException If retrieval of the database classes, or mapping of the tables was unsuccesfull.
 *//* www.  j  ava 2 s  . c om*/
private DbaseFacade() throws SQLException {
    if (FeatureServerConfiguration.getInstance() == null
            || FeatureServerConfiguration.getInstance().isInvalid()) {
        throw new SQLException("Invalid FeatureServer configuration");
    }
    String connectionString = FeatureServerConfiguration.getInstance()
            .getHibernateProperty("hibernate.connection.url");
    String user = FeatureServerConfiguration.getInstance()
            .getHibernateProperty("hibernate.connection.username");
    String password = FeatureServerConfiguration.getInstance()
            .getHibernateProperty("hibernate.connection.password");
    Connection dbConnection = DriverManager.getConnection(connectionString, user, password);
    DatabaseMetaData databaseMetaData = dbConnection.getMetaData();
    String schema = FeatureServerConfiguration.getInstance().getDbaseSchema();
    ResultSet resultSet = databaseMetaData.getTables(null, schema, null, new String[] { "TABLE", "VIEW" });
    ArrayList<String> names = new ArrayList<String>();
    while (resultSet.next()) {
        names.add(resultSet.getString("TABLE_NAME"));
    }
    Configuration newConfig = new Configuration();
    for (String property : FeatureServerConfiguration.getInstance().getHibernateProperties()) {
        newConfig.setProperty(property,
                FeatureServerConfiguration.getInstance().getHibernateProperty(property));
    }

    mappedTables = FeatureServerConfiguration.getInstance().includedTables(names);
    // We may only invoke this once, since currently the automapper crashes if a table was already mapped in the
    // past. Since this call is present in the private constructor which is only called in the singleton method
    // there is no problem.
    Document tableMapping = AutoMapper.map(dbConnection, null, schema, mappedTables);
    resultSet.close();
    dbConnection.close();
    newConfig.addXML(tableMapping.asXML());

    HSConfiguration configuration = new HSConfiguration();
    this.sessionFactory = newConfig.buildSessionFactory();
    LOGGER.info("Sessionfactory created: " + sessionFactory);
    configuration.configure(newConfig);
}

From source file:org.jboss.dashboard.database.hibernate.HibernateInitializer.java

License:Apache License

protected void loadHibernateDescriptors(Configuration hbmConfig) throws IOException {
    Set<File> jars = Application.lookup().getJarFiles();
    for (File jar : jars) {
        ZipFile zf = new ZipFile(jar);
        for (Enumeration en = zf.entries(); en.hasMoreElements();) {
            ZipEntry entry = (ZipEntry) en.nextElement();
            String entryName = entry.getName();
            if (entryName.endsWith("hbm.xml") && !entry.isDirectory()) {
                InputStream is = zf.getInputStream(entry);
                String xml = readXMLForFile(entryName, is);
                xml = processXMLContents(xml);
                hbmConfig.addXML(xml);
            }//from   ww w .j  a va  2s. c  o  m
        }
    }
}

From source file:org.openbravo.dal.core.DalSessionFactoryController.java

License:Open Source License

@Override
protected void mapModel(Configuration configuration) {
    final String mapping = DalMappingGenerator.getInstance().generateMapping();
    log.debug("Generated mapping: ");
    log.debug(mapping);/*from   w  w w  .  j  av a  2  s.co  m*/
    configuration.addXML(mapping);
}

From source file:org.sipfoundry.sipxconfig.common.DynamicSessionFactoryBean.java

License:Contributor Agreement License

/**
 * Finds all subclasesses of baseClass in the bean factory and binds them to the same table as
 * base class using bean id as a discriminator value.
 *
 * @param config hibernate config that will be modified
 * @param baseClass base class - needs to be already mapped statically
 *//*  w w w . j ava  2 s  .c om*/
protected void bindSubclasses(Configuration config, Class baseClass) {
    String[] beanDefinitionNames = m_beanFactory.getBeanNamesForType(baseClass);
    for (String beanId : beanDefinitionNames) {
        Class subClass = m_beanFactory.getType(beanId);
        if (subClass == baseClass) {
            continue; // skip baseclass which is already mapped
        }
        String mapping = xmlMapping(baseClass, subClass, beanId);
        config.addXML(mapping);
    }
}

From source file:org.xwiki.platform.patchservice.storage.PatchStorage.java

License:Open Source License

private void init(XWikiContext context) throws XWikiException {
    System.err.println("storage initializing");
    XWikiHibernateStore storage = ((XWikiHibernateStore) context.getWiki().getNotCacheStore());
    Configuration config = storage.getConfiguration();
    try {/*from ww w .j  a  va 2 s  . c om*/
        // Make sure the schema is updated to include the Patch mapping
        config.setProperty("hibernate.hbm2ddl.auto", "update");
        try {
            config.addXML(IOUtils.toString(this.getClass().getResourceAsStream(MAPPING_FILENAME)));
        } catch (DuplicateMappingException e) {
        }
        this.factory = config.buildSessionFactory();
    } catch (MappingException e) {
        throw new XWikiException(XWikiException.MODULE_XWIKI_STORE,
                XWikiException.ERROR_XWIKI_STORE_HIBERNATE_INVALID_MAPPING, "Invalid Patch mapping file", e);
    } catch (HibernateException e) {
        throw new XWikiException(XWikiException.MODULE_XWIKI_STORE, XWikiException.ERROR_XWIKI_UNKNOWN,
                "Unknown error initializing the Patch storage", e);
    } catch (IOException e) {
        throw new XWikiException(XWikiException.MODULE_XWIKI_STORE,
                XWikiException.ERROR_XWIKI_STORE_HIBERNATE_INVALID_MAPPING, "Cannot load Patch mapping file",
                e);
    }
    System.err.println("storage initialized");
}

From source file:uk.co.modularaudio.util.hibernate.generator.GeneratorHelper.java

License:Open Source License

/**
 * Generate the DDL for one component implementing the IsHibernatePersistedComponent interface
 * @param component The persisted component we wish to obtain the DDL for
 * @param dialectName Which hibernate dialect should be used
 * @param destinationDirectory The output directory
 * @param outputFileName The output filename
 * @throws IOException On errors reading the related hbm files for a component or writing the output DDL file
 *//*  w w  w.  j  a  v a 2 s  .  c om*/
public void generateDDL(final ComponentWithHibernatePersistence component, final String dialectName,
        final String destinationDirectory, final String outputFileName) throws IOException {
    final Configuration configuration = new Configuration();
    final List<HibernatePersistedBeanDefinition> listHBM = component.listHibernatePersistedBeanDefinitions();
    for (final HibernatePersistedBeanDefinition hbmDefinition : listHBM) {
        final String originalHbmResourceName = hbmDefinition.getHbmResourceName();

        final InputStream hbmInputStream = Thread.currentThread().getContextClassLoader()
                .getResourceAsStream(originalHbmResourceName);

        final String originalHbmString = IOUtils.basicReadInputStreamUTF8(hbmInputStream);

        final String newHbmString = TableNamePrefixer.prefixTableNames(originalHbmString,
                hbmDefinition.getPersistedBeanTablePrefix());

        configuration.addXML(newHbmString);

    }
    configureAndGenerate(dialectName, destinationDirectory, outputFileName, configuration);
}