List of usage examples for org.hibernate.cfg Configuration setProperty
public Configuration setProperty(String propertyName, String value)
From source file:com.almuradev.backpack.backend.DatabaseManager.java
License:MIT License
public static void init(Path databaseRootPath, String name) { final Configuration configuration = new Configuration(); configuration.setProperty("hibernate.connection.provider_class", CONNECTION_PROVIDER); configuration.setProperty("hibernate.dialect", DIALECT); configuration.setProperty("hibernate.hikari.dataSourceClassName", DRIVER_CLASSPATH); configuration.setProperty("hibernate.hikari.dataSource.url", DATA_SOURCE_PREFIX + databaseRootPath.toString() + File.separator + name + DATA_SOURCE_SUFFIX); configuration.setProperty("hibernate.hbm2ddl.auto", AUTO_SCHEMA_MODE); registerTables(configuration);//from w w w . j a va 2 s .co m sessionFactory = configuration.buildSessionFactory( new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build()); }
From source file:com.amalto.core.query.StorageFullTextTest.java
License:Open Source License
public void testGenerateIdFetchSize() throws Exception { // Test "stream resultset" RDBMSDataSource dataSource = new RDBMSDataSource("TestDataSource", "MySQL", "", "", "", 0, 0, "", "", false, "update", false, new HashMap(), "", "", null, "", "", "", false); Configuration configuration = new Configuration(); configuration.setProperty(Environment.STATEMENT_FETCH_SIZE, "1000"); HibernateStorage storage = new HibernateStorage("HibernateStorage"); storage.init(getDatasource("RDBMS-1-NO-FT")); storage.prepare(repository, Collections.<Expression>emptySet(), false, false); Class storageClass = storage.getClass(); Field dataSourceField = storageClass.getDeclaredField("dataSource"); dataSourceField.setAccessible(true); dataSourceField.set(storage, dataSource); Field configurationField = storageClass.getDeclaredField("configuration"); configurationField.setAccessible(true); configurationField.set(storage, configuration); Method generateIdFetchSizeMethod = storageClass.getDeclaredMethod("generateIdFetchSize", null); generateIdFetchSizeMethod.setAccessible(true); assertEquals(Integer.MIN_VALUE, generateIdFetchSizeMethod.invoke(storage, null)); // Test config batch size dataSource = new RDBMSDataSource("TestDataSource", "H2", "", "", "", 0, 0, "", "", false, "update", false, new HashMap(), "", "", null, "", "", "", false); storage = new HibernateStorage("HibernateStorage"); storage.init(getDatasource("RDBMS-1-NO-FT")); storage.prepare(repository, Collections.<Expression>emptySet(), false, false); storageClass = storage.getClass();/* www .j ava2s.c o m*/ dataSourceField = storageClass.getDeclaredField("dataSource"); dataSourceField.setAccessible(true); dataSourceField.set(storage, dataSource); configurationField = storageClass.getDeclaredField("configuration"); configurationField.setAccessible(true); configurationField.set(storage, configuration); assertEquals(1000, generateIdFetchSizeMethod.invoke(storage, null)); // Test default batch size configuration = new Configuration(); configurationField = storageClass.getDeclaredField("configuration"); configurationField.setAccessible(true); configurationField.set(storage, configuration); assertEquals(500, generateIdFetchSizeMethod.invoke(storage, null)); }
From source file:com.arnau.persistencia.hibernate.HibernateUtil.java
public static synchronized void buildSessionFactory() { if (sessionFactory == null) { Configuration configuration = new Configuration(); configuration.configure();//from w ww . ja v a 2s .c o m configuration.setProperty("hibernate.current_session_context_class", "thread"); configuration.setProperty("hibernate.dialect", "org.hibernate.dialect.HSQLDialect"); ServiceRegistry serviceRegistry = new ServiceRegistryBuilder() .applySettings(configuration.getProperties()).buildServiceRegistry(); sessionFactory = configuration.buildSessionFactory(serviceRegistry); } }
From source file:com.arnau.persistencia.hibernate.HibernateUtil.java
public static void crearBD() { Configuration configuration = new Configuration(); configuration.configure();/*from w w w. ja v a2 s. c o m*/ configuration.setProperty("hibernate.current_session_context_class", "thread"); configuration.setProperty("hibernate.dialect", "org.hibernate.dialect.HSQLDialect"); //Si segundo parmetro del mtodo create est a true, Hibernate crea la BD pero borra los datos new org.hibernate.tool.hbm2ddl.SchemaExport(configuration).setOutputFile("script.sql").setDelimiter(";") .create(true, true); }
From source file:com.astonish.dropwizard.routing.hibernate.RoutingSessionFactoryFactory.java
License:Apache License
/** * Builds a {@link SessionFactory}//from w w w . j av a 2s . c o m * @param bundle * the bundle * @param dbConfig * the dbconfig * @param connectionProvider * the connection provider * @param properties * the hibernate properties * @param entities * the persistent entities * @return {@link SessionFactory} */ private SessionFactory buildSessionFactory(RoutingHibernateBundle<?> bundle, DataSourceFactory dbConfig, ConnectionProvider connectionProvider, Map<String, String> properties, List<Class<?>> entities) { final Configuration configuration = new Configuration(); configuration.setProperty(AvailableSettings.CURRENT_SESSION_CONTEXT_CLASS, "managed"); configuration.setProperty(AvailableSettings.USE_SQL_COMMENTS, Boolean.toString(dbConfig.isAutoCommentsEnabled())); configuration.setProperty(AvailableSettings.USE_GET_GENERATED_KEYS, "true"); configuration.setProperty(AvailableSettings.GENERATE_STATISTICS, "true"); configuration.setProperty(AvailableSettings.USE_REFLECTION_OPTIMIZER, "true"); configuration.setProperty(AvailableSettings.ORDER_UPDATES, "true"); configuration.setProperty(AvailableSettings.ORDER_INSERTS, "true"); configuration.setProperty(AvailableSettings.USE_NEW_ID_GENERATOR_MAPPINGS, "true"); configuration.setProperty("jadira.usertype.autoRegisterUserTypes", "true"); for (Map.Entry<String, String> property : properties.entrySet()) { configuration.setProperty(property.getKey(), property.getValue()); } addAnnotatedClasses(configuration, entities); bundle.configure(configuration); final ServiceRegistry registry = new StandardServiceRegistryBuilder() .addService(ConnectionProvider.class, connectionProvider).applySettings(properties).build(); return configuration.buildSessionFactory(registry); }
From source file:com.cgi.poc.dw.dao.HibernateUtil.java
public HibernateUtil() { try {//from ww w . j a v a 2s . c o m File newConfiguration = new File(CONFIG_PATH); Yaml yaml = new Yaml(); InputStream is = new FileInputStream(newConfiguration); LinkedHashMap yamlParsers = (LinkedHashMap<String, ArrayList>) yaml.load(is); LinkedHashMap databaseCfg = (LinkedHashMap<String, ArrayList>) yamlParsers.get("database"); String driver = (String) databaseCfg.get("driverClass"); String dbUrl = (String) databaseCfg.get("url"); String userName = (String) databaseCfg.get("user"); String userPwd = (String) databaseCfg.get("password"); Configuration configuration = new Configuration(); // need to be able to read config file to get the uname/pwd for testing.. can't // use in memory DB b/c we need json, and geometry types which are not supported // by h2 configuration.setProperty("connection.driver_class", driver); configuration.setProperty("hibernate.connection.url", dbUrl); configuration.setProperty("hibernate.connection.username", userName); configuration.setProperty("hibernate.connection.password", userPwd); configuration.setProperty("hibernate.current_session_context_class", "thread"); configuration.addAnnotatedClass(User.class); configuration.addAnnotatedClass(FireEvent.class); configuration.addAnnotatedClass(EventEarthquake.class); configuration.addAnnotatedClass(EventWeather.class); configuration.addAnnotatedClass(EventFlood.class); configuration.addAnnotatedClass(EventHurricane.class); configuration.addAnnotatedClass(EventTsunami.class); configuration.addAnnotatedClass(EventVolcano.class); configuration.addAnnotatedClass(EventNotification.class); configuration.addAnnotatedClass(EventNotificationZipcode.class); configuration.addAnnotatedClass(EventNotificationUser.class); sessionFactory = configuration.buildSessionFactory(); openSession = sessionFactory.openSession(); Connection sqlConnection = ((SessionImpl) openSession).connection(); sessionFactory.getCurrentSession(); JdbcConnection conn = new JdbcConnection(sqlConnection); Database database = DatabaseFactory.getInstance().findCorrectDatabaseImplementation(conn); Liquibase liquibase = new Liquibase("migrations.xml", new ClassLoaderResourceAccessor(), database); String ctx = null; liquibase.update(ctx); } catch (Exception ex) { Logger.getLogger(HibernateUtil.class.getName()).log(Level.SEVERE, null, ex); System.exit(0); } }
From source file:com.cloud.bridge.util.CloudSessionFactory.java
License:Open Source License
private CloudSessionFactory() { Configuration cfg = new Configuration(); File file = ConfigurationHelper.findConfigurationFile("hibernate.cfg.xml"); File propertiesFile = ConfigurationHelper.findConfigurationFile("db.properties"); Properties dbProp = null;//from w w w .j a v a2 s.co m String dbName = null; String dbHost = null; String dbUser = null; String dbPassword = null; String dbPort = null; if (null != propertiesFile) { if (EncryptionSecretKeyCheckerUtil.useEncryption()) { StandardPBEStringEncryptor encryptor = EncryptionSecretKeyCheckerUtil.getEncryptor(); dbProp = new EncryptableProperties(encryptor); } else { dbProp = new Properties(); } try { dbProp.load(new FileInputStream(propertiesFile)); } catch (FileNotFoundException e) { logger.warn("Unable to open properties file: " + propertiesFile.getAbsolutePath(), e); } catch (IOException e) { logger.warn("Unable to read properties file: " + propertiesFile.getAbsolutePath(), e); } } // // we are packaging hibernate mapping files along with the class files, // make sure class loader use the same class path when initializing hibernate mapping. // This is important when we are deploying and testing at different environment (Tomcat/JUnit test runner) // if (file != null && dbProp != null) { Thread.currentThread().setContextClassLoader(this.getClass().getClassLoader()); cfg.configure(file); dbHost = dbProp.getProperty("db.cloud.host"); dbName = dbProp.getProperty("db.awsapi.name"); dbUser = dbProp.getProperty("db.cloud.username"); dbPassword = dbProp.getProperty("db.cloud.password"); dbPort = dbProp.getProperty("db.cloud.port"); cfg.setProperty("hibernate.connection.url", "jdbc:mysql://" + dbHost + ":" + dbPort + "/" + dbName); cfg.setProperty("hibernate.connection.username", dbUser); cfg.setProperty("hibernate.connection.password", dbPassword); factory = cfg.buildSessionFactory(); } else { logger.warn("Unable to open load db configuration"); throw new RuntimeException("nable to open load db configuration"); } }
From source file:com.cloud.bridge.util.CloudStackSessionFactory.java
License:Open Source License
private CloudStackSessionFactory() { Configuration cfg = new Configuration(); File file = ConfigurationHelper.findConfigurationFile("CloudStack.cfg.xml"); File propertiesFile = ConfigurationHelper.findConfigurationFile("db.properties"); Properties dbProp = null;//from ww w .j av a 2 s. c o m String dbName = null; String dbHost = null; String dbUser = null; String dbPassword = null; String dbPort = null; if (null != propertiesFile) { if (EncryptionSecretKeyCheckerUtil.useEncryption()) { StandardPBEStringEncryptor encryptor = EncryptionSecretKeyCheckerUtil.getEncryptor(); dbProp = new EncryptableProperties(encryptor); } else { dbProp = new Properties(); } try { dbProp.load(new FileInputStream(propertiesFile)); } catch (FileNotFoundException e) { logger.warn("Unable to open properties file: " + propertiesFile.getAbsolutePath(), e); } catch (IOException e) { logger.warn("Unable to read properties file: " + propertiesFile.getAbsolutePath(), e); } } // // we are packaging hibernate mapping files along with the class files, // make sure class loader use the same class path when initializing hibernate mapping. // This is important when we are deploying and testing at different environment (Tomcat/JUnit test runner) // if (file != null && dbProp != null) { Thread.currentThread().setContextClassLoader(this.getClass().getClassLoader()); cfg.configure(file); dbHost = dbProp.getProperty("db.cloud.host"); dbName = dbProp.getProperty("db.cloud.name"); dbUser = dbProp.getProperty("db.cloud.username"); dbPassword = dbProp.getProperty("db.cloud.password"); dbPort = dbProp.getProperty("db.cloud.port"); cfg.setProperty("hibernate.connection.url", "jdbc:mysql://" + dbHost + ":" + dbPort + "/" + dbName); cfg.setProperty("hibernate.connection.username", dbUser); cfg.setProperty("hibernate.connection.password", dbPassword); factory = cfg.buildSessionFactory(); } else { logger.warn("Unable to open load db configuration"); throw new RuntimeException("nable to open load db configuration"); } }
From source file:com.corundumstudio.core.extensions.hibernate.BaseTest.java
License:Apache License
protected static void initHibernate() { Properties props = buildDatabaseConfiguration("db1"); Configuration cfg = new Configuration(); cfg.setProperty(Environment.GENERATE_STATISTICS, "true"); cfg.setProperty(AvailableSettings.HBM2DDL_AUTO, "create"); cfg.setProperty(AvailableSettings.CACHE_REGION_FACTORY, InfinispanRegionFactory.class.getName()); cfg.setProperty(InfinispanRegionFactory.INFINISPAN_CONFIG_RESOURCE_PROP, "infinispan.xml"); cfg.setProperty(AvailableSettings.QUERY_CACHE_FACTORY, DynamicQueryCacheFactory.class.getName()); cfg.setProperty(Environment.USE_SECOND_LEVEL_CACHE, "true"); cfg.setProperty(Environment.USE_QUERY_CACHE, "true"); cfg.addAnnotatedClass(SimpleEntity.class); cfg.buildMappings();/*from w ww . j a va 2 s . c o m*/ ServiceRegistryBuilder sb = new ServiceRegistryBuilder(); ServiceRegistry serviceRegistry = sb.applySettings(props).buildServiceRegistry(); sessionFactory = (SessionFactoryImplementor) cfg.buildSessionFactory(serviceRegistry); EventListenerRegistry registry = sessionFactory.getServiceRegistry() .getService(EventListenerRegistry.class); registry.getEventListenerGroup(EventType.POST_UPDATE).appendListener(queryCacheEntityListener); registry.getEventListenerGroup(EventType.POST_INSERT).appendListener(queryCacheEntityListener); registry.getEventListenerGroup(EventType.POST_DELETE).appendListener(queryCacheEntityListener); }
From source file:com.db4o.drs.test.hibernate.HibernateUtil.java
License:Open Source License
/** * Create a unique Configuration with the underlying database guaranteed to be * empty./*from w w w . j av a2s. c o m*/ * * @return configuration */ public static Configuration createNewDbConfig() { Configuration configuration = new Configuration().configure(HSQL_CFG_XML); String url = JDBC_URL_HEAD + jdbcUrlCounter++; return configuration.setProperty(Environment.URL, url); }