List of usage examples for org.hibernate.cfg Configuration setProperty
public Configuration setProperty(String propertyName, String value)
From source file:com.floreantpos.util.datamigrate.DataMigrationWindow.java
License:Open Source License
protected void migrate() { sourceDatabase = sourceDbPanel.getDatabase(); destDatabase = destDbPanel.getDatabase(); sourceConnectString = sourceDbPanel.getConnectString(); destConnectString = destDbPanel.getConnectString(); Configuration sourceConfiguration = _RootDAO.getNewConfiguration(null); sourceConfiguration = sourceConfiguration.setProperty("hibernate.dialect", //$NON-NLS-1$ sourceDatabase.getHibernateDialect()); sourceConfiguration = sourceConfiguration.setProperty("hibernate.connection.driver_class", //$NON-NLS-1$ sourceDatabase.getHibernateConnectionDriverClass()); sourceConfiguration = sourceConfiguration.setProperty("hibernate.connection.url", sourceConnectString); //$NON-NLS-1$ sourceConfiguration = sourceConfiguration.setProperty("hibernate.connection.username", //$NON-NLS-1$ sourceDbPanel.getUser());//from w w w. j a va 2 s. co m sourceConfiguration = sourceConfiguration.setProperty("hibernate.connection.password", //$NON-NLS-1$ sourceDbPanel.getPass()); Configuration destConfiguration = _RootDAO.getNewConfiguration(null); destConfiguration = destConfiguration.setProperty("hibernate.dialect", destDatabase.getHibernateDialect()); //$NON-NLS-1$ destConfiguration = destConfiguration.setProperty("hibernate.connection.driver_class", //$NON-NLS-1$ destDatabase.getHibernateConnectionDriverClass()); destConfiguration = destConfiguration.setProperty("hibernate.connection.url", destConnectString); //$NON-NLS-1$ destConfiguration = destConfiguration.setProperty("hibernate.connection.username", destDbPanel.getUser()); //$NON-NLS-1$ destConfiguration = destConfiguration.setProperty("hibernate.connection.password", destDbPanel.getPass()); //$NON-NLS-1$ SessionFactory sourceSessionFactory = sourceConfiguration.buildSessionFactory(); SessionFactory destSessionFactory = destConfiguration.buildSessionFactory(); Session sourceSession = sourceSessionFactory.openSession(); Session destSession = destSessionFactory.openSession(); Transaction transaction = destSession.beginTransaction(); List<MenuCategory> categories = MenuCategoryDAO.getInstance().findAll(sourceSession); for (MenuCategory menuCategory : categories) { MenuCategory m = new MenuCategory(); m.setName(menuCategory.getName()); m.setTranslatedName(menuCategory.getTranslatedName()); m.setBeverage(menuCategory.isBeverage()); m.setVisible(menuCategory.isVisible()); PosLog.info(DataMigrationWindow.class, "" + menuCategory); MenuCategoryDAO.getInstance().save(m, destSession); } transaction.commit(); destSession.close(); PosLog.info(getClass(), "done"); //$NON-NLS-1$ }
From source file:com.fpmislata.banco.persistence.dao.impl.hibernate.HibernateUtil.java
public static void buildSessionFactory() { Configuration configuration = new Configuration(); configuration.configure();/*from w ww .jav a2 s. com*/ configuration.setProperty("hibernate.current_session_context_class", "thread"); ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder() .applySettings(configuration.getProperties()).build(); sessionFactory = configuration.buildSessionFactory(serviceRegistry); }
From source file:com.fpmislata.seguros.datos.hibernate.HibernateUtil.java
License:Apache License
public static synchronized void buildSessionFactory() { if (sessionFactory == null) { Configuration configuration = new Configuration(); configuration.configure();//from www. j ava 2s. com configuration.setProperty("hibernate.current_session_context_class", "thread"); ServiceRegistry serviceRegistry = new ServiceRegistryBuilder() .applySettings(configuration.getProperties()).buildServiceRegistry(); sessionFactory = configuration.buildSessionFactory(serviceRegistry); } }
From source file:com.frameworkset.common.poolman.hibernate.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) { this.configTimeDataSourceHolder.set(dataSource); }// w w w. j av a2s.c om // 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)); try { if (overrideClassLoader) { currentThread.setContextClassLoader(this.beanClassLoader); } 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.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. Properties temp = new Properties(); temp.putAll(this.hibernateProperties); config.addProperties(temp); } if (dataSource != null) { Class providerClass = LocalDataSourceConnectionProvider.class; config.setProperty(Environment.CONNECTION_PROVIDER, providerClass.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 = SimpleStringUtil .commaDelimitedListToStringArray(this.entityCacheStrategies.getProperty(className)); if (strategyAndRegion.length > 1) { // method signature declares return type as Configuration on Hibernate 3.6 // but as void on Hibernate 3.3 and 3.5 Method setCacheConcurrencyStrategy = Configuration.class .getMethod("setCacheConcurrencyStrategy", String.class, String.class, String.class); ReflectionUtils.invokeMethod(setCacheConcurrencyStrategy, config, new Object[] { 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 = SimpleStringUtil .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 (overrideClassLoader) { // Reset original thread context ClassLoader. currentThread.setContextClassLoader(threadContextClassLoader); } configTimeDataSourceHolder.set(null); } }
From source file:com.gemstone.gemfire.modules.HibernateJUnitTest.java
License:Apache License
public static SessionFactory getSessionFactory(Properties overrideProps) { System.setProperty(DistributionConfig.GEMFIRE_PREFIX + "home", "GEMFIREHOME"); Configuration cfg = new Configuration(); cfg.setProperty("hibernate.dialect", "org.hibernate.dialect.HSQLDialect"); cfg.setProperty("hibernate.connection.driver_class", "org.hsqldb.jdbcDriver"); // cfg.setProperty("hibernate.connection.url", "jdbc:hsqldb:mem:test"); cfg.setProperty("hibernate.connection.url", jdbcURL); cfg.setProperty("hibernate.connection.username", "sa"); cfg.setProperty("hibernate.connection.password", ""); cfg.setProperty("hibernate.connection.pool_size", "1"); cfg.setProperty("hibernate.connection.autocommit", "true"); cfg.setProperty("hibernate.hbm2ddl.auto", "update"); cfg.setProperty("hibernate.cache.region.factory_class", "com.gemstone.gemfire.modules.hibernate.GemFireRegionFactory"); cfg.setProperty("hibernate.show_sql", "true"); cfg.setProperty("hibernate.cache.use_query_cache", "true"); //cfg.setProperty("gemfire.mcast-port", AvailablePort.getRandomAvailablePort(AvailablePort.JGROUPS)+""); cfg.setProperty(DistributionConfig.GEMFIRE_PREFIX + MCAST_PORT, "0"); cfg.setProperty(DistributionConfig.GEMFIRE_PREFIX + STATISTIC_SAMPLING_ENABLED, "true"); cfg.setProperty(DistributionConfig.GEMFIRE_PREFIX + LOG_FILE, gemfireLog); cfg.setProperty(DistributionConfig.GEMFIRE_PREFIX + "writable-working-dir", tmpDir.getPath()); //cfg.setProperty("gemfire.statistic-archive-file", "plugin-stats-file.gfs"); //cfg.setProperty("gemfire.default-client-region-attributes-id", "CACHING_PROXY"); //cfg.setProperty("gemfire.cache-topology", "client-server"); //cfg.setProperty("gemfire.locators", "localhost[5432]"); //cfg.setProperty("gemfire.log-level", "fine"); // cfg.setProperty("", ""); cfg.addClass(Person.class); cfg.addClass(Event.class); if (overrideProps != null) { Iterator it = overrideProps.keySet().iterator(); while (it.hasNext()) { String key = (String) it.next(); cfg.setProperty(key, overrideProps.getProperty(key)); }//from w ww.ja v a 2 s . com } return cfg.buildSessionFactory(); }
From source file:com.github.antennaesdk.messageserver.db.H2.H2Database.java
License:Apache License
public void generateSchemaAndCreateTables(SimpleDriverDataSource dataSource) { // Get the tables that are already in the DATABASE List<String> tables = new ArrayList<>(); try {//from w ww . j a va2s . c o m Connection connection = dataSource.getConnection(); DatabaseMetaData databaseMetadata = connection.getMetaData(); ResultSet resultSet = databaseMetadata.getTables(null, null, null, new String[] { "TABLE" }); while (resultSet.next()) { String table = resultSet.getString(3); logger.info("Table : " + table + " ... exists"); tables.add(table); } } catch (SQLException e) { e.printStackTrace(); } // Get the tables that are needed from Entity Classes List<Class> tablesToCreate = new ArrayList<>(); for (Class<?> c : entityClasses) { // get the table names Table table = c.getAnnotation(Table.class); logger.info("Entity: " + c.getName() + " , Table: " + table.name()); boolean isExisting = false; for (String dbTable : tables) { if (dbTable.equals(table.name())) { isExisting = true; break; } } if (!isExisting) { // these tables must be created tablesToCreate.add(c); } } // Check whether the tables need to be created... if (tablesToCreate.size() == 0) { logger.info("Tables already exist... "); return; } else { logger.info("Creating tables..."); } //create a minimal configuration org.hibernate.cfg.Configuration cfg = new org.hibernate.cfg.Configuration(); cfg.setProperty("hibernate.dialect", "org.hibernate.dialect.H2Dialect"); cfg.setProperty("hibernate.hbm2ddl.auto", "create"); // create a temporary file to write the DDL File ddlFile = null; try { File dir = getDirectoryFromClasspath(); ddlFile = File.createTempFile("H2_", ".SQL", dir); ddlFile.deleteOnExit(); } catch (IOException e) { e.printStackTrace(); } // add the tables to be created for (Class c : tablesToCreate) { cfg.addAnnotatedClass(c); } //build all the mappings, before calling the AuditConfiguration cfg.buildMappings(); cfg.getProperties().setProperty(AvailableSettings.HBM2DDL_IMPORT_FILES, ddlFile.getName()); cfg.getProperties().setProperty("hibernate.connection.driver_class", "org.h2.Driver"); cfg.getProperties().setProperty("hibernate.connection.url", dataSource.getUrl()); cfg.getProperties().setProperty("hibernate.connection.username", dataSource.getUsername()); cfg.getProperties().setProperty("hibernate.connection.password", dataSource.getPassword()); //execute the export SchemaExport export = new SchemaExport(cfg); export.setDelimiter(";"); export.setFormat(true); // create the tables in the DB and show the DDL in console export.create(true, true); }
From source file:com.googlecode.sarasvati.example.hib.HibTestSetup.java
License:Open Source License
public static void init(final boolean createSchema) throws Exception { final Configuration config = new Configuration(); if (createSchema) { config.setProperty(Environment.HBM2DDL_AUTO, "create-drop"); }/*w ww . j av a 2 s . com*/ HibEngine.addToConfiguration(config, false); config.addAnnotatedClass(HibExampleTaskNode.class); config.addAnnotatedClass(Task.class); config.addAnnotatedClass(InitNode.class); config.addAnnotatedClass(DumpNode.class); config.addAnnotatedClass(AsyncNode.class); URL url = HibTestSetup.class.getClassLoader().getResource("hibernate.cfg.xml"); if (url == null) { System.out.println("ERROR: No hibernate.cfg.xml found in classpath!\n" + "\tIn order to run the examples, you must create hibernate.cfg.xml in the examples/ directory.\n" + "\tYou can use the entries in conf/ as a starting point."); System.exit(-1); } config.configure(url); sessionFactory = config.buildSessionFactory(); }
From source file:com.ikon.dao.HibernateUtil.java
License:Open Source License
/** * Get instance/*from ww w .j av a 2 s . c o m*/ */ public static SessionFactory getSessionFactory(String hbm2ddl) { if (sessionFactory == null) { try { // Configure Hibernate Configuration cfg = getConfiguration().configure(); cfg.setProperty("hibernate.dialect", Config.HIBERNATE_DIALECT); cfg.setProperty("hibernate.connection.datasource", Config.HIBERNATE_DATASOURCE); cfg.setProperty("hibernate.hbm2ddl.auto", hbm2ddl); cfg.setProperty("hibernate.show_sql", Config.HIBERNATE_SHOW_SQL); cfg.setProperty("hibernate.generate_statistics", Config.HIBERNATE_STATISTICS); cfg.setProperty("hibernate.search.analyzer", Config.HIBERNATE_SEARCH_ANALYZER); cfg.setProperty("hibernate.search.default.directory_provider", "org.hibernate.search.store.FSDirectoryProvider"); cfg.setProperty("hibernate.search.default.indexBase", Config.HIBERNATE_SEARCH_INDEX_HOME); cfg.setProperty("hibernate.search.default.optimizer.operation_limit.max", "500"); cfg.setProperty("hibernate.search.default.optimizer.transaction_limit.max", "75"); cfg.setProperty("hibernate.worker.execution", "async"); // http://relation.to/Bloggers/PostgreSQLAndBLOBs // cfg.setProperty("hibernate.jdbc.use_streams_for_binary", "false"); // Show configuration log.info("Hibernate 'hibernate.dialect' = {}", cfg.getProperty("hibernate.dialect")); log.info("Hibernate 'hibernate.connection.datasource' = {}", cfg.getProperty("hibernate.connection.datasource")); log.info("Hibernate 'hibernate.hbm2ddl.auto' = {}", cfg.getProperty("hibernate.hbm2ddl.auto")); log.info("Hibernate 'hibernate.show_sql' = {}", cfg.getProperty("hibernate.show_sql")); log.info("Hibernate 'hibernate.generate_statistics' = {}", cfg.getProperty("hibernate.generate_statistics")); log.info("Hibernate 'hibernate.search.default.directory_provider' = {}", cfg.getProperty("hibernate.search.default.directory_provider")); log.info("Hibernate 'hibernate.search.default.indexBase' = {}", cfg.getProperty("hibernate.search.default.indexBase")); if (HBM2DDL_CREATE.equals(hbm2ddl)) { // In case of database schema creation, also clean filesystem data. // This means, conversion cache, file datastore and Lucene indexes. log.info("Cleaning filesystem data from: {}", Config.REPOSITORY_HOME); FileUtils.deleteQuietly(new File(Config.REPOSITORY_HOME)); } // Create database schema, if needed sessionFactory = cfg.buildSessionFactory(); if (HBM2DDL_CREATE.equals(hbm2ddl)) { log.info("Executing specific import for: {}", Config.HIBERNATE_DIALECT); InputStream is = ConfigUtils.getResourceAsStream("default.sql"); String adapted = DatabaseDialectAdapter.dialectAdapter(is, Config.HIBERNATE_DIALECT); executeImport(new StringReader(adapted)); IOUtils.closeQuietly(is); } if (HBM2DDL_CREATE.equals(hbm2ddl) || HBM2DDL_UPDATE.equals(hbm2ddl)) { // Create or update translations for (String res : ConfigUtils.getResources("i18n")) { String oldTrans = null; String langId = null; // Preserve translation changes if (HBM2DDL_UPDATE.equals(hbm2ddl)) { langId = FileUtils.getFileName(res); log.info("Preserving translations for: {}", langId); oldTrans = preserveTranslations(langId); } InputStream isLang = ConfigUtils.getResourceAsStream("i18n/" + res); log.info("Importing translation: {}", res); executeImport(new InputStreamReader(isLang)); IOUtils.closeQuietly(isLang); // Apply previous translation changes if (HBM2DDL_UPDATE.equals(hbm2ddl)) { if (oldTrans != null) { log.info("Restoring translations for: {}", langId); executeImport(new StringReader(oldTrans)); } } } // Replace "create" or "update" by "none" to prevent repository reset on restart if (Boolean.parseBoolean(Config.HIBERNATE_CREATE_AUTOFIX)) { log.info("Executing Hibernate create autofix"); hibernateCreateAutofix(Config.HOME_DIR + "/" + Config.ikon_CONFIG); } else { log.info("Hibernate create autofix not executed because of {}={}", Config.PROPERTY_HIBERNATE_CREATE_AUTOFIX, Config.HIBERNATE_CREATE_AUTOFIX); } } } catch (HibernateException e) { log.error(e.getMessage(), e); throw new ExceptionInInitializerError(e); } catch (URISyntaxException e) { log.error(e.getMessage(), e); throw new ExceptionInInitializerError(e); } catch (IOException e) { log.error(e.getMessage(), e); throw new ExceptionInInitializerError(e); } } return sessionFactory; }
From source file:com.ikon.dao.HibernateUtil.java
License:Open Source License
/** * Generate database schema and initial data for a defined dialect *///from w w w . ja v a 2 s . c om public static void generateDatabase(String dialect) throws IOException { // Configure Hibernate log.info("Exporting Database Schema..."); String dbSchema = EnvironmentDetector.getUserHome() + "/schema.sql"; Configuration cfg = getConfiguration().configure(); cfg.setProperty("hibernate.dialect", dialect); SchemaExport se = new SchemaExport(cfg); se.setOutputFile(dbSchema); se.setDelimiter(";"); se.setFormat(false); se.create(false, false); log.info("Database Schema exported to {}", dbSchema); String initialData = new File("").getAbsolutePath() + "/src/main/resources/default.sql"; log.info("Exporting Initial Data from '{}'...", initialData); String initData = EnvironmentDetector.getUserHome() + "/data.sql"; FileInputStream fis = new FileInputStream(initialData); String ret = DatabaseDialectAdapter.dialectAdapter(fis, dialect); FileWriter fw = new FileWriter(initData); IOUtils.write(ret, fw); fw.flush(); fw.close(); log.info("Initial Data exported to {}", initData); }
From source file:com.jeroensteenbeeke.hyperion.data.TestPersistenceModel.java
License:Open Source License
@Before public void initHibernate() { Configuration config = new Configuration(); config = config.addAnnotatedClass(Lolcat.class); config = config.setProperty("hibernate.hbm2ddl.auto", "create"); config = config.setProperty("hibernate.dialect", "org.hibernate.dialect.H2Dialect"); config = config.setProperty("hibernate.show_sql", "true"); config = config.setProperty("hibernate.connection.driver_class", "org.h2.Driver"); config = config.setProperty("hibernate.connection.url", "jdbc:h2:mem:tysan"); config = config.setProperty("hibernate.connection.username", "sa"); config = config.setProperty("hibernate.connection.password", ""); config = config.setProperty("hibernate.connection.pool_size", "50"); config = config.setProperty("hibernate.connection.provider_class", "org.hibernate.connection.DriverManagerConnectionProvider"); // config = config.setProperty("hibernate.c3p0.min_size", "5"); // config = config.setProperty("hibernate.c3p0.max_size", "20"); // config = config.setProperty("hibernate.c3p0.timeout", "1800"); // config = config.setProperty("hibernate.c3p0.max_statements", "50"); final ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder() .applySettings(config.getProperties()).build(); sf = config.buildSessionFactory(serviceRegistry); }