Example usage for org.hibernate.cfg Configuration setProperties

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

Introduction

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

Prototype

public Configuration setProperties(Properties properties) 

Source Link

Document

Specify a completely new set of properties

Usage

From source file:com.liferay.portal.spring.hibernate.PortalHibernateConfiguration.java

License:Open Source License

protected Configuration newConfiguration() {
    Configuration configuration = new Configuration();

    try {/*  w  w w .j a va2 s .  c  o m*/
        String[] resources = getConfigurationResources();

        for (String resource : resources) {
            try {
                readResource(configuration, resource);
            } catch (Exception e2) {
                if (_log.isWarnEnabled()) {
                    _log.warn(e2, e2);
                }
            }
        }

        configuration.setProperties(PropsUtil.getProperties());

        if (Validator.isNull(PropsValues.HIBERNATE_DIALECT)) {
            String dialect = determineDialect();

            configuration.setProperty("hibernate.dialect", dialect);
        }

        DB db = DBFactoryUtil.getDB();

        String dbType = db.getType();

        if (dbType.equals(DB.TYPE_HYPERSONIC)) {
            //configuration.setProperty("hibernate.jdbc.batch_size", "0");
        }
    } catch (Exception e1) {
        _log.error(e1, e1);
    }

    Properties hibernateProperties = getHibernateProperties();

    if (hibernateProperties != null) {
        for (Map.Entry<Object, Object> entry : hibernateProperties.entrySet()) {

            String key = (String) entry.getKey();
            String value = (String) entry.getValue();

            configuration.setProperty(key, value);
        }
    }

    return configuration;
}

From source file:com.maydesk.base.util.CledaConnector.java

License:Mozilla Public License

private void createSessionFactory() {
    Properties props = new Properties();

    try {//from www .j  av  a  2 s  .c o m
        Context ctx = new InitialContext();
        DataSource ds = (DataSource) ctx.lookup("java:comp/env/jdbc/maydesk_db");
        props.put("hibernate.connection.datasource", ds);
    } catch (NamingException e) {
        e.printStackTrace();
    }

    props.put("hibernate.cglib.use_reflection_optimizer", true);
    props.put("hibernate.show_sql", false);
    props.put("hibernate.hbm2ddl.auto", "update");
    props.put("transaction.factory_class", "org.hibernate.transaction.JDBCTransactionFactory");

    props.put("hibernate.dialect", "org.hibernate.dialect.MySQLDialect");

    // Create config
    Configuration config = new Configuration();
    config.setProperties(props);

    config.setInterceptor(new AuditInterceptor());
    config.setNamingStrategy(new ImprovedNamingStrategy());
    config.setProperties(props);

    // registering model
    registerModels(config, "com.maydesk.base.model");
    registerModels(config, "com.maydesk.social.model");

    ServiceRegistryBuilder serviceRegistryBuilder = new ServiceRegistryBuilder();

    ServiceRegistry serviceRegistry = serviceRegistryBuilder.applySettings(props).buildServiceRegistry();
    sessionFactory = config.buildSessionFactory(serviceRegistry);
}

From source file:com.mysema.query.jpa.codegen.JPADomainExporterTest.java

License:Apache License

private Metamodel convert(Configuration config) {
    ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(props).buildServiceRegistry();

    config.setProperties(props);
    config.buildMappings();//w w  w  .  j a va  2  s .  com
    SessionFactory sessionFactory = config.buildSessionFactory(serviceRegistry);
    return MetamodelImpl.buildMetamodel(config.getClassMappings(), (SessionFactoryImplementor) sessionFactory,
            true);
}

From source file:com.mysema.testutil.HibernateTestRunner.java

License:Apache License

private void start() throws Exception {
    Configuration cfg = new Configuration();
    for (Class<?> cl : Domain.classes) {
        cfg.addAnnotatedClass(cl);/*from   w w  w.j a  va2s . co m*/
    }
    String mode = Mode.mode.get() + ".properties";
    isDerby = mode.contains("derby");
    if (isDerby) {
        Class.forName("org.apache.derby.jdbc.EmbeddedDriver").newInstance();
    }
    Properties props = new Properties();
    InputStream is = HibernateTestRunner.class.getResourceAsStream(mode);
    if (is == null) {
        throw new IllegalArgumentException("No configuration available at classpath:" + mode);
    }
    props.load(is);
    cfg.setProperties(props);
    sessionFactory = cfg.buildSessionFactory();
    session = sessionFactory.openSession();
    session.beginTransaction();
}

From source file:com.okasamastarr.CreateDdlMojo.java

License:Apache License

public void execute() throws MojoExecutionException {
    ClassLoader oldClassLoader = Thread.currentThread().getContextClassLoader();
    try {/*ww w .  ja v  a 2s  .c om*/
        Thread.currentThread().setContextClassLoader(createProjectClassLoader());
        Configuration cfg = createHibernateConfiguration(persistenceUnit);

        Properties props = new Properties();
        if (propFile != null) {
            props.load(new FileInputStream(propFile));
        }
        cfg.setProperties(props);
        if (dialect != null) {
            props.setProperty("hibernate.dialect", dialect);
        }
        if (importFile != null) {
            props.setProperty(AvailableSettings.HBM2DDL_IMPORT_FILES, importFile);
        }

        SchemaExport schemaExport = new SchemaExport(cfg).setOutputFile(outputFile).setFormat(format)
                .setDelimiter(delimeter);
        schemaExport.execute(script, export, drop, create);
    } catch (Throwable ex) {
        throw new MojoExecutionException("Failed to create DDL schema", ex);
    } finally {
        Thread.currentThread().setContextClassLoader(oldClassLoader);
    }
}

From source file:com.querydsl.jpa.testutil.HibernateTestRunner.java

License:Apache License

private void start() throws Exception {
    Configuration cfg = new Configuration();
    for (Class<?> cl : Domain.classes) {
        cfg.addAnnotatedClass(cl);//from   w  w w .  j ava2  s .c  o m
    }
    String mode = Mode.mode.get() + ".properties";
    isDerby = mode.contains("derby");
    if (isDerby) {
        Class.forName("org.apache.derby.jdbc.EmbeddedDriver").newInstance();
    }
    Properties props = new Properties();
    InputStream is = HibernateTestRunner.class.getResourceAsStream(mode);
    if (is == null) {
        throw new IllegalArgumentException("No configuration available at classpath:" + mode);
    }
    props.load(is);
    ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(props).build();
    cfg.setProperties(props);
    sessionFactory = cfg.buildSessionFactory(serviceRegistry);
    session = sessionFactory.openSession();
    session.beginTransaction();
}

From source file:com.sam.moca.db.hibernate.HibernateTools.java

License:Open Source License

synchronized public static SessionFactory getSessionFactory(final MocaContext ctx) {
    if (_factory == null) {
        Configuration cfg = new Configuration();

        // First, load up default properties stored in MOCA 
        Properties props = new Properties();
        try {//from  w  w  w  . j a v  a  2s.  c  o m
            _loadProperties(props, HibernateTools.class.getResourceAsStream("resources/hibernate.properties"));
        } catch (IOException e) {
            ctx.logWarning("Unable to load hibernate properties: " + e);
            _sqlLogger.debug("Unable to load hibernate properties", e);
        }

        // Next, default the database dialect, based on MOCA's idea
        // of the database type.
        String dbType = ctx.getDb().getDbType();

        if (dbType.equals("ORACLE")) {
            props.setProperty("hibernate.dialect", "org.hibernate.dialect.Oracle10gDialect");
        } else if (dbType.equals("MSSQL")) {
            props.setProperty("hibernate.dialect", "com.sam.moca.db.hibernate.UnicodeSQLServerDialect");
        } else if (dbType.equals("H2")) {
            props.setProperty("hibernate.dialect", "org.hibernate.dialect.H2Dialect");
        }

        SystemContext systemContext = ServerUtils.globalContext();

        // We get the data files in reverse.
        File[] files = systemContext.getDataFiles(new FilenameFilter() {

            @Override
            public boolean accept(File dir, String name) {
                if (name.equals("hibernate.properties")) {
                    return true;
                }
                return false;
            }

        }, true);

        // For each directory in the list, look for a
        // hibernate.properties file.
        for (File propFile : files) {
            if (propFile.canRead()) {
                try {
                    ctx.trace(MocaTrace.SQL, "Loading Properties file: " + propFile);
                    _loadProperties(props, new FileInputStream(propFile));
                } catch (IOException e) {
                    ctx.logWarning("Unable to load properties " + propFile + ": " + e);
                    _sqlLogger.debug("Unable to load hibernate properties", e);
                } catch (HibernateException e) {
                    ctx.logWarning("Unable to load properties " + propFile + ": " + e);
                    _sqlLogger.debug("Unable to load hibernate properties", e);
                }
            }
        }

        cfg.setProperties(props);

        // We get the data files in reverse.
        files = systemContext.getDataFiles(new FilenameFilter() {

            @Override
            public boolean accept(File dir, String name) {
                if (name.equals("hibernate.cfg.xml")) {
                    return true;
                }
                return false;
            }

        }, true);

        // Now look for hibernate config files in each mappings directory.
        for (File xmlFile : files) {
            if (xmlFile.canRead()) {
                try {
                    ctx.trace(MocaTrace.SQL, "Loading config file: " + xmlFile);
                    cfg.configure(xmlFile);
                } catch (HibernateException e) {
                    ctx.logWarning("Unable to load config file " + xmlFile + ": " + e);
                    _sqlLogger.debug("Unable to load hibernate config", e);
                }
            }
        }

        _factory = cfg.buildSessionFactory();

        StatisticsService statsMBean = new StatisticsService();
        statsMBean.setSessionFactory(_factory);

        Exception excp = null;
        MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
        try {
            mBeanServer.registerMBean(statsMBean, new ObjectName("Hibernate:application=Statistics"));
        } catch (InstanceAlreadyExistsException e) {
            excp = e;
        } catch (MBeanRegistrationException e) {
            excp = e;
        } catch (NotCompliantMBeanException e) {
            excp = e;
        } catch (MalformedObjectNameException e) {
            excp = e;
        }

        if (excp != null) {
            _sqlLogger.warn("Failed to export Hibernate Statistics "
                    + "Service.  Runtime statistics will not be viewable " + "from MBeans!", excp);
        }
    }

    return _factory;

}

From source file:com.wavemaker.runtime.data.util.DataServiceUtils.java

License:Open Source License

private static void setup(Configuration cfg, Properties p) {
    p = DataServiceUtils.toHibernateConnectionProperties(p);
    cfg.setProperties(p);
}

From source file:de.eod.jliki.db.DBManager.java

License:Open Source License

/**
 * Creates instance.<br/>//from  www  .  ja v a2s  .  c  o  m
 * @param tableClasses the classes (with annotations) that can be stored in the database
 */
public DBManager(final Class<?>[] tableClasses) {
    final String jdbcDriver = ConfigManager.getInstance().getConfig().getDbConfig().getDriver();
    final String dbUrl = ConfigManager.getInstance().getConfig().getDbConfig().getUrl();
    final String dbName = ConfigManager.getInstance().getConfig().getDbConfig().getDbName();
    final String dbUser = ConfigManager.getInstance().getConfig().getDbConfig().getUser();
    final String dbPass = ConfigManager.getInstance().getConfig().getDbConfig().getPassword();
    final Map<String, String> addParams = ConfigManager.getInstance().getConfig().getDbConfig()
            .getAdditionalParams();

    String connectUrl = dbUrl;
    if (!dbUrl.endsWith("/")) {
        connectUrl += "/";
    }
    connectUrl += dbName;

    final Properties dbProps = new Properties();
    dbProps.setProperty("hibernate.connection.driver_class", jdbcDriver);
    dbProps.setProperty("hibernate.connection.url", connectUrl);
    dbProps.setProperty("hibernate.connection.username", dbUser);
    dbProps.setProperty("hibernate.connection.password", dbPass);
    dbProps.setProperty("hibernate.c3p0.min_size", "5");
    dbProps.setProperty("hibernate.c3p0.max_size", "20");
    dbProps.setProperty("hibernate.c3p0.timeout", "1800");
    dbProps.setProperty("hibernate.c3p0.max_statements", "50");

    if (addParams != null) {
        for (final Map.Entry<String, String> entry : addParams.entrySet()) {
            dbProps.setProperty(entry.getKey(), entry.getValue());
        }
    }

    final Configuration hibConfig = new Configuration();
    hibConfig.setProperties(dbProps);

    for (final Class<?> clazz : tableClasses) {
        hibConfig.addAnnotatedClass(clazz);
    }

    this.hibSessionFactory = hibConfig.buildSessionFactory();
}

From source file:de.fhg.fokus.odp.rssservlet.utils.HibernateConfig.java

License:Open Source License

/**
 * Gets the connection.//from  w w w  .j  a va  2  s  .c o  m
 * 
 * @param contextPath
 *            the context path
 * @return the connection
 */
public Configuration getConnection(ServletContext context) {

    Properties props = new Properties();
    props.setProperty("hibernate.connection.driver_class",
            LiferayPropsUtil.getValueFromKey("jdbc.default.driverClassName", context));
    props.setProperty("hibernate.connection.url",
            LiferayPropsUtil.getValueFromKey("jdbc.default.url", context));
    props.setProperty("hibernate.connection.username",
            LiferayPropsUtil.getValueFromKey("jdbc.default.username", context));
    props.setProperty("hibernate.connection.password",
            LiferayPropsUtil.getValueFromKey("jdbc.default.password", context));
    props.setProperty("hibernate.connection.pool_size", "20");

    props.setProperty("hibernate.c3p0.min_size", "5");
    props.setProperty("hibernate.c3p0.max_size", "20");
    props.setProperty("hibernate.c3p0.timeout", "300");
    props.setProperty("hibernate.c3p0.max_statements", "50");

    LOG.debug("Using the following props for hibernate: {}", props);

    Configuration conf = new Configuration();
    conf.setProperties(props);
    conf.addAnnotatedClass(CommentaryEntity.class);
    return conf;
}