Example usage for org.hibernate.cfg Configuration setProperty

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

Introduction

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

Prototype

public Configuration setProperty(String propertyName, String value) 

Source Link

Document

Set a property value by name

Usage

From source file:jmanager.dal.entity.HibernateUtil.java

private static Configuration getConfiguration() {
    Configuration cfg = new Configuration();
    cfg.addAnnotatedClass(Contact.class);
    cfg.setProperty("hibernate.connection.driver_class", ApplicationConstants.DatabaseConfig.Driver.GetValue());
    cfg.setProperty("hibernate.connection.url", ApplicationConstants.DatabaseConfig.URL.GetValue());
    cfg.setProperty("hibernate.connection.username", ApplicationConstants.DatabaseConfig.UserName.GetValue());
    cfg.setProperty("hibernate.connection.password", ApplicationConstants.DatabaseConfig.Password.GetValue());
    cfg.setProperty("hibernate.show_sql", ApplicationConstants.DatabaseConfig.ShowSQL.GetValue());
    cfg.setProperty("hibernate.dialect", ApplicationConstants.DatabaseConfig.Dialect.GetValue());
    cfg.setProperty("hibernate.hbm2ddl.auto", ApplicationConstants.DatabaseConfig.Auto.GetValue());
    cfg.setProperty("hibernate.cache.provider_class", ApplicationConstants.DatabaseConfig.Provider.GetValue());
    cfg.setProperty("hibernate.current_session_context_class",
            ApplicationConstants.DatabaseConfig.Session.GetValue());
    return cfg;//w w w.j  av  a 2 s  .c om
}

From source file:jworkspace.weather.ImportPipelineTest.java

License:Open Source License

@Before
public void before() {
    // setup the session factory
    Configuration configuration = new Configuration();
    configuration.addAnnotatedClass(Observation.class);
    configuration.setProperty("hibernate.dialect", "org.hibernate.dialect.H2Dialect");
    configuration.setProperty("hibernate.connection.driver_class", "org.h2.Driver");
    configuration.setProperty("hibernate.connection.url", "jdbc:h2:./test/resources/db/mem");
    configuration.setProperty("hibernate.hbm2ddl.auto", "create");
    sessionFactory = configuration.buildSessionFactory();
    session = sessionFactory.openSession();
}

From source file:kr.debop4j.data.mongodb.test.loading.LoadSelectedColumnsCollectionTest.java

License:Apache License

@Override
protected void configure(Configuration cfg) {
    super.configure(cfg);
    cfg.setProperty(Environment.MONGODB_ASSOCIATIONS_STORE, AssociationStorage.COLLECTION.name());
}

From source file:lk.dialoglab.ezcash.util.HibernateUtil.java

private static void setSessionFactory(DBInfo dbInfo) {
    try {/*from w  w  w . j a  v  a  2 s  .c  o  m*/

        Configuration conf = new Configuration().configure();
        String url = "jdbc:mysql://" + dbInfo.getServer() + ":" + dbInfo.getPort() + "/" + dbInfo.getDbName();
        //System.out.println("dbInfo: " + dbInfo);
        System.out.println("url to open++++++++++++++++: " + url + " dbInfo:" + dbInfo.getUsername()
                + " dbInfo: " + dbInfo.getPassword());
        conf.setProperty("hibernate.connection.url", url);
        conf.setProperty("hibernate.connection.username", dbInfo.getUsername());
        conf.setProperty("hibernate.connection.password", dbInfo.getPassword());
        serviceRegistry = new StandardServiceRegistryBuilder().applySettings(conf.getProperties()).build();
        sessionFactory = conf.buildSessionFactory(serviceRegistry);

    }

    catch (Throwable ex) {

        System.err.println("Initial SessionFactory creation failed." + ex);
        throw new ExceptionInInitializerError(ex);
    }
}

From source file:lt.emasina.resthub.factory.ConnectionManager.java

License:Open Source License

public Session getSession(String name) {
    if (!factories.containsKey(name)) {

        Configuration cfg = new Configuration();
        cfg.configure();/*from  ww w  . j  a v  a2  s  .  co m*/

        cfg.setProperty(PROPERTY_URL, cf.getUrl(name));
        cfg.setProperty(PROPERTY_USERNAME, cf.getUsername(name));
        cfg.setProperty(PROPERTY_PASSWORD, cf.getPassword(name));

        if (log.isDebugEnabled()) {
            cfg.setProperty(PROPERTY_SHOWSQL, "true");
            cfg.setProperty(PROPERTY_FORMATSQL, "true");
        }

        if (log.isDebugEnabled()) {
            for (Map.Entry<Object, Object> e : cfg.getProperties().entrySet()) {
                log.debug(String.format("%s property: %s = %s", name, e.getKey(), e.getValue()));
            }
        }

        ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
                .applySettings(cfg.getProperties()).build();
        factories.put(name, cfg.buildSessionFactory(serviceRegistry));

    }
    return factories.get(name).openSession();
}

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 {
    /*//from  ww w .  ja v  a 2 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:main.java.edu.isistan.genCom.redSocial.dao.HibernateUtil.java

License:Open Source License

/**
 * Establece una nueva configuracin en base a los datos de la conexin
 * /* w w  w. ja v a 2s .c  o m*/
 * @param myConnectionUrl
 * @param myUserName
 * @param myPassword
 */
public static void setConfig(String myConnectionUrl, String myUserName, String myPassword) throws Exception {
    // modificar los datos del hibernate.cfg.xml
    Configuration configuration = new Configuration();
    configuration.configure();

    HibernateUtil.myConnectionUrl = myConnectionUrl;
    HibernateUtil.myUserName = myUserName;
    HibernateUtil.myPassword = myPassword;

    configuration.setProperty("hibernate.connection.url", myConnectionUrl);
    configuration.setProperty("hibernate.connection.username", myUserName);
    configuration.setProperty("hibernate.connection.password", myPassword);

    // Crea el nuevo buildsessionfactory
    configuration.setNamingStrategy(DefaultNamingStrategy.INSTANCE);
    SessionFactory sf = configuration.buildSessionFactory();

    // TODO Prueba la conexin

    if (!conecta()) {
        throw new Exception("No se ha podido establecer la conexin. Por favor verifique los datos.");
    }

    // Establece la configuracin como definitiva
    sessionFactory = sf;
}

From source file:main.java.info.jtrac.hibernate.SchemaHelper.java

License:Apache License

/**
 * create tables using the given Hibernate configuration
 *///  www  .j  av  a 2s  . co  m
public void createSchema() {
    Configuration cfg = new Configuration();
    if (StringUtils.hasText(dataSourceJndiName)) {
        cfg.setProperty("hibernate.connection.datasource", dataSourceJndiName);
    } else {
        cfg.setProperty("hibernate.connection.driver_class", driverClassName);
        cfg.setProperty("hibernate.connection.url", url);
        cfg.setProperty("hibernate.connection.username", username);
        cfg.setProperty("hibernate.connection.password", password);
    }
    cfg.setProperty("hibernate.dialect", hibernateDialect);
    for (String resource : mappingResources) {
        cfg.addResource(resource);
    }
    logger.info("begin database schema creation =========================");
    new SchemaUpdate(cfg).execute(true, true);
    logger.info("end database schema creation ===========================");
}

From source file:mnzw.projekty.HiberUtil.java

public static SessionFactory getXMLSessionFactory() {
    try {/*from   ww w  .j  a v  a2 s  . c  om*/
        File mappingDir = new File("src\\mnzw\\projekty\\mapowanie");
        Configuration config = new Configuration().configure();

        config.setProperty("hibernate.show_sql", "false");
        config.addDirectory(mappingDir);

        StandardServiceRegistryBuilder registryBuilder = new StandardServiceRegistryBuilder();
        registryBuilder.applySettings(config.getProperties());
        ServiceRegistry serviceRegistry = registryBuilder.build();

        SessionFactory sf = config.buildSessionFactory(serviceRegistry);

        return (sf);
    } catch (Throwable ex) {

        System.err.println("Initial SessionFactory creation failed." + ex);
        throw new ExceptionInInitializerError(ex);
    }
}

From source file:mnzw.projekty.HiberUtil.java

public static SessionFactory getANNSessionFactory() {
    try {//from   ww  w .  ja  v  a 2 s  .  co m
        Configuration config = new Configuration().configure();
        config.setProperty("hibernate.show_sql", "false");

        config.addAnnotatedClass(Jezyki.class).addAnnotatedClass(JezykProgramowania.class)
                .addAnnotatedClass(Osoba.class).addAnnotatedClass(Kierownik.class)
                .addAnnotatedClass(Programista.class).addAnnotatedClass(Projekt.class)
                .addAnnotatedClass(Zapotrzebowanie.class).addAnnotatedClass(Zatrudnienie.class);

        config.setProperty("hibernate.show_sql", "false");
        //config.setProperty("hibernate.hbm2ddl.auto", "none");

        StandardServiceRegistryBuilder registryBuilder = new StandardServiceRegistryBuilder();
        registryBuilder.applySettings(config.getProperties());
        ServiceRegistry serviceRegistry = registryBuilder.build();

        SessionFactory sf = config.buildSessionFactory(serviceRegistry);

        return (sf);
    } catch (Throwable ex) {

        System.err.println("Initial SessionFactory creation failed." + ex);
        throw new ExceptionInInitializerError(ex);
    }
}