List of usage examples for org.hibernate.cfg Configuration setProperty
public Configuration setProperty(String propertyName, String value)
From source file:org.ngrinder.infra.init.DataUpdaterTest.java
License:Apache License
@Test public void exportDatabaseSchema() throws IOException { PersistenceUnitInfo persistenceUnitInfo = entityManagerFactory.getPersistenceUnitInfo(); for (Database each : Database.values()) { Map<?, ?> jpaPropertyMap = entityManagerFactory.getJpaPropertyMap(); Configuration configuration = new Ejb3Configuration().configure(persistenceUnitInfo, jpaPropertyMap) .getHibernateConfiguration(); configuration.setProperty(Environment.DIALECT, each.getDialect()); SchemaExport schema = new SchemaExport(configuration); File parentFile = new ClassPathResource("/ngrinder_datachange_logfile/db.changelog.xml").getFile() .getParentFile();//ww w . j a va2 s . c o m parentFile.mkdirs(); File file = new File(parentFile, "schema-" + each.name().toLowerCase() + ".sql"); System.out.println(file.getAbsolutePath()); schema.setOutputFile(file.getAbsolutePath()); schema.create(true, false); } }
From source file:org.onebusaway.admin.service.bundle.task.GtfsArchiveTask.java
License:Apache License
private Configuration getConfiguration() { try {/* www . j a v a 2 s . c om*/ Context initialContext = new InitialContext(); Context environmentContext = (Context) initialContext.lookup("java:comp/env"); DataSource ds = (DataSource) environmentContext.lookup("jdbc/archiveDB"); if (ds == null) { _log.error("unable to locate expected datasource jdbc/archiveDB"); return null; } Configuration config = new Configuration(); config.setProperty("hibernate.connection.datasource", "java:comp/env/jdbc/archiveDB"); config.setProperty("hibernate.connection.pool_size", "1"); config.setProperty("hibernate.cache.provider_class", "org.hibernate.cache.NoCacheProvider"); config.setProperty("hibernate.hbm2ddl.auto", "update"); config.addResource("org/onebusaway/gtfs/model/GtfsArchiveMapping.hibernate.xml"); config.addResource("org/onebusaway/gtfs/impl/HibernateGtfsRelationalDaoImpl.hibernate.xml"); //performance tuning config.setProperty("hibernate.jdbc.batch_size", "4000"); config.setProperty("hibernate.jdbc.fetch_size", "64"); config.setProperty("hibernate.order_inserts", "true"); config.setProperty("hibernate.order_updates", "true"); config.setProperty("hibernate.cache.use_second_level_cache", "false"); config.setProperty("hibernate.generate_statistics", "false"); config.setProperty("hibernate.cache.use_query_cache", "false"); return config; } catch (Throwable t) { _log.error("configuration exception:", t); return null; } }
From source file:org.onebusaway.gtfs.GtfsDatabaseLoaderMain.java
License:Apache License
private void run(String[] args) throws IOException { CommandLine cli = parseCommandLineOptions(args); args = cli.getArgs();/* w w w .jav a 2 s. c om*/ if (args.length != 1) { printUsage(); System.exit(-1); } Configuration config = new Configuration(); config.setProperty("hibernate.connection.driver_class", cli.getOptionValue(ARG_DRIVER_CLASS)); config.setProperty("hibernate.connection.url", cli.getOptionValue(ARG_URL)); if (cli.hasOption(ARG_USERNAME)) { config.setProperty("hibernate.connection.username", cli.getOptionValue(ARG_USERNAME)); } if (cli.hasOption(ARG_PASSWORD)) { config.setProperty("hibernate.connection.password", cli.getOptionValue(ARG_PASSWORD)); } config.setProperty("hibernate.connection.pool_size", "1"); config.setProperty("hibernate.cache.provider_class", "org.hibernate.cache.NoCacheProvider"); config.setProperty("hibernate.hbm2ddl.auto", "update"); config.addResource("org/onebusaway/gtfs/model/GtfsMapping.hibernate.xml"); config.addResource("org/onebusaway/gtfs/impl/HibernateGtfsRelationalDaoImpl.hibernate.xml"); SessionFactory sessionFactory = config.buildSessionFactory(); HibernateGtfsFactory factory = new HibernateGtfsFactory(sessionFactory); GtfsReader reader = new GtfsReader(); reader.setInputLocation(new File(args[0])); GtfsMutableRelationalDao dao = factory.getDao(); reader.setEntityStore(dao); reader.run(); reader.close(); }
From source file:org.openbp.server.persistence.hibernate.HibernateDDLGenerator.java
License:Apache License
/** * Generates the DDL files.//from w w w . java2 s .co m */ public void generate() { ProcessServer processServer = new ProcessServerFactory().createProcessServer(); PersistenceContextProvider provider = processServer.getEngine().getPersistenceContextProvider(); if (provider == null) { String msg = LogUtil.error(getClass(), "No persistence context provider configured."); System.err.println(msg); System.exit(1); return; } if (!(provider instanceof HibernatePersistenceContextProvider)) { String msg = LogUtil.error(getClass(), "Configured persistence context provider no no Hibernate provider (class $0).", provider.getClass().getName()); System.err.println(msg); System.exit(1); return; } Configuration configuration = ((HibernatePersistenceContextProvider) provider) .createHibernateConfiguration(); if (dialect != null) { String adapterClassName = null; if (dialect.indexOf('.') >= 0) { adapterClassName = dialect; } else { adapterClassName = "org.hibernate.dialect." + dialect + "Dialect"; } configuration.setProperty("hibernate.dialect", adapterClassName); } SchemaExport se = new SchemaExport(configuration); se.setFormat(true); se.setDelimiter(";"); String outputFile; if ((outputFile = prepareOutputFile(getDdlCreateFileName())) != null) { se.setOutputFile(outputFile); se.execute(false, false, false, true); } if ((outputFile = prepareOutputFile(getDdlDropFileName())) != null) { se.setOutputFile(outputFile); se.execute(false, false, true, false); } }
From source file:org.openmrs.util.databasechange.DatabaseUpgradeTestUtil.java
License:Mozilla Public License
public SessionFactory buildSessionFactory() { Configuration config = new Configuration().configure(); //H2 version we use behaves differently from H2Dialect in Hibernate so we provide our implementation config.setProperty(Environment.DIALECT, H2LessStrictDialect.class.getName()); config.setProperty(Environment.URL, connectionUrl); config.setProperty(Environment.DRIVER, "org.h2.Driver"); config.setProperty(Environment.USER, "sa"); config.setProperty(Environment.PASS, "sa"); config.setProperty(Environment.USE_SECOND_LEVEL_CACHE, "false"); config.setProperty(Environment.USE_QUERY_CACHE, "false"); //Let's validate HBMs against the actual schema config.setProperty(Environment.HBM2DDL_AUTO, "validate"); return config.buildSessionFactory(); }
From source file:org.openremote.model.persistence.jpa.H2.java
License:Open Source License
/** * Creates an H2 configuration for Hibernate session factory. * * @param persistenceMode/* www.ja va2s. com*/ * see {@link PersistenceMode} * * @param dbName * file path for the database storage -- only relevant when the persistence mode * is {@link PersistenceMode#ON_DISK} * * @param config * Hibernate configuration to use as the base * * @return * Hibernate session factory */ private static SessionFactory createSessionFactory(PersistenceMode persistenceMode, String dbName, Configuration config) { config.setProperty("hibernate.connection.url", "jdbc:h2:mem:db1;DB_CLOSE_DELAY=-1;MVCC=TRUE"); if (persistenceMode == PersistenceMode.ON_DISK) { config.setProperty("hibernate.connection.url", "jdbc:h2:" + dbName); } config.setProperty("hibernate.connection.driver_class", "org.h2.Driver"); config.setProperty("hibernate.connection.username", "sa"); config.setProperty("hibernate.connection.pool_size", "3"); config.setProperty("hibernate.cache.provider_class", "org.hibernate.cache.internal.NoCacheProvider"); config.setProperty("hibernate.dialect", "org.hibernate.dialect.H2Dialect"); config.setProperty("hibernate.hbm2ddl.auto", "create"); config.setProperty("hibernate.current_session_context_class", "managed"); ServiceRegistry registry = new StandardServiceRegistryBuilder().applySettings(config.getProperties()) .build(); return config.buildSessionFactory(registry); }
From source file:org.opentestsystem.airose.db.session.DBSetUp.java
License:Open Source License
@SuppressWarnings("deprecation") public void startUp() throws UninitializedException { /*//w w w . ja v a 2 s . c om * most of the DB configuration is carried out from hibernate.cfg.xml except * possibly for the DB URL which may be overwritten from the main * configuration file. */ AbstractConfiguration applicationConfiguration = ConfigurationFactory.getConfiguration(); Configuration cfg = new Configuration().configure("hibernate.cfg.xml"); if (applicationConfiguration.getDBURL() != null) cfg.setProperty("hibernate.connection.url", applicationConfiguration.getDBURL()); // A SessionFactory is set up once for an application mSessionFactory = cfg.buildSessionFactory(); // configures // settings from // hibernate.cfg.xml }
From source file:org.opentides.util.HibernateUtil.java
License:Apache License
/** * Static initializer to establish database connection. *//* w ww . j a v a2s . c o m*/ private static void initialize() { try { URL[] urls = ClasspathUrlFinder.findResourceBases(persistenceFile); List<URL> toAdd = new ArrayList<URL>(); List<URL> finalUrls = new ArrayList<URL>(); for (URL url : urls) { LOGGER.debug("URL is : [" + url.getPath() + "] with protocol: [" + url.getProtocol() + "] with file: [" + url.getFile() + "]"); String file = url.getFile(); if (!file.startsWith("file:")) { file = "file:" + file; } if ("zip".equals(url.getProtocol())) { toAdd.add(new URL("jar", url.getHost(), url.getPort(), file)); } else { toAdd.add(url); } } finalUrls.addAll(toAdd); for (URL url : finalUrls) { LOGGER.debug("URL full path: [" + url.toString() + "]"); LOGGER.debug("Final URL is : [" + url.getPath() + "] with protocol: [" + url.getProtocol() + "] with file: [" + url.getFile() + "]"); } AnnotationDB db = new AnnotationDB(); db.scanArchives(finalUrls.toArray(new URL[finalUrls.size()])); Set<String> entityClasses = db.getAnnotationIndex().get(javax.persistence.Entity.class.getName()); // Create the SessionFactory Configuration ac = new Configuration(); Properties properties = XMLPersistenceUtil.getProperties(persistenceFile, persistenceUnitName); ac.setProperties(properties); if (StringUtil.isEmpty(jndiName)) { ac.setProperty("hibernate.connection.driver_class", driverClassName); ac.setProperty("hibernate.connection.url", url); ac.setProperty("hibernate.connection.username", username); ac.setProperty("hibernate.connection.password", password); } else { LOGGER.debug("JNDI not empty. [" + jndiName + "] using persistence [" + persistenceFile + "]"); ac.setProperty("hibernate.connection.datasource", jndiName); } for (String clazz : entityClasses) { LOGGER.debug("Entity Class : [" + clazz + "]"); ac.addAnnotatedClass(Class.forName(clazz)); } ac.addAnnotatedClass(Class.forName("org.opentides.bean.AuditLog")); ac.addAnnotatedClass(Class.forName("org.opentides.bean.BaseEntity")); ac.addAnnotatedClass(Class.forName("org.opentides.bean.FileInfo")); ac.addAnnotatedClass(Class.forName("org.opentides.bean.SystemCodes")); ac.addAnnotatedClass(Class.forName("org.opentides.bean.Widget")); ac.addAnnotatedClass(Class.forName("org.opentides.bean.UserWidgets")); ac.addAnnotatedClass(Class.forName("org.opentides.bean.user.BaseUser")); ac.addAnnotatedClass(Class.forName("org.opentides.bean.PasswordReset")); ac.addAnnotatedClass(Class.forName("org.opentides.bean.user.UserRole")); ac.addAnnotatedClass(Class.forName("org.opentides.bean.user.UserCredential")); ac.addAnnotatedClass(Class.forName("org.opentides.bean.user.UserGroup")); ac.addAnnotatedClass(Class.forName("org.opentides.bean.UserDefinedRecord")); ac.addAnnotatedClass(Class.forName("org.opentides.bean.UserDefinedField")); sessionFactory = ac.buildSessionFactory(); } catch (Throwable ex) { // Make sure you log the exception, as it might be swallowed System.err.println("Initial SessionFactory creation failed." + ex); throw new ExceptionInInitializerError(ex); } }
From source file:org.osaf.cosmo.db.DbInitializer.java
License:Apache License
private void validateSchema() { try {/*from w w w . jav a 2 s . c o m*/ // Workaround for Spring 2.0.1 LocalSessionFactoryBean not having // access to DataSource. Should be fixed in Spring 2.0.2. SimpleConnectionProvider.setConnection(datasource.getConnection()); Configuration config = localSessionFactory.getConfiguration(); config.setProperty(Environment.CONNECTION_PROVIDER, "org.osaf.cosmo.hibernate.SimpleConnectionProvider"); log.info("validating schema"); new SchemaValidator(config).validate(); log.info("schema validation passed"); } catch (SQLException sqle) { log.error("could not get database metadata", sqle); throw new RuntimeException("Error retreiving database metadata"); } catch (RuntimeException rte) { log.error("error validating schema", rte); throw rte; } }
From source file:org.ow2.bonita.search.SearchUtil.java
License:Open Source License
public static void addSearchConfiguration(final Configuration configuration) { boolean disable = disableSearchConfiguration(configuration); if (disable) { if (LOG.isLoggable(Level.INFO)) { LOG.info("Disable Bonita Indexes"); }/* w w w . java 2 s . c o m*/ } else { if (LOG.isLoggable(Level.INFO)) { LOG.info("Configuring indexes"); } SearchMapping mapping = new SearchMapping(); mapping.entity(InternalProcessDefinition.class).indexed().indexName("process_definition") .property("dbid", ElementType.FIELD).documentId().name(ProcessDefinitionIndex.DBID) .entity(LightProcessDefinitionImpl.class).property("uuid", ElementType.FIELD).field() .name(ProcessDefinitionIndex.UUID).bridge(UUIDFieldBridge.class) .property("categoryNames", ElementType.METHOD).field() .name(ProcessDefinitionIndex.CATEGORY_NAME).bridge(StringSetFieldBridge.class) .entity(NamedElementImpl.class).property("name", ElementType.METHOD).field() .name(ProcessDefinitionIndex.NAME).entity(DescriptionElementImpl.class) // share with All DescriptionElement: processes, groups, ... .property("description", ElementType.METHOD).field().name(ProcessDefinitionIndex.DESCRIPTION) .entity(InternalProcessInstance.class).indexed().indexName("process_instance") .property("dbid", ElementType.FIELD).documentId().name(ProcessInstanceIndex.DBID) .entity(ProcessInstanceImpl.class).property("commentFeed", ElementType.METHOD).indexEmbedded() .property("involvedUsers", ElementType.METHOD).field().name(ProcessInstanceIndex.INVOLVED_USER) .bridge(StringSetFieldBridge.class).property("activities", ElementType.METHOD).indexEmbedded() .property("lastKnownVariableValues", ElementType.METHOD).field().name("variable") .bridge(ObjectMapFieldBridge.class).property("activeUsers", ElementType.METHOD).field() .name(ProcessInstanceIndex.ACTIVE_USER).bridge(StringSetFieldBridge.class) .entity(LightProcessInstanceImpl.class).property("nb", ElementType.FIELD).field() .name(ProcessInstanceIndex.NB).property("startedBy", ElementType.METHOD).field() .name(ProcessInstanceIndex.STARTED_BY).property("endedBy", ElementType.METHOD).field() .name(ProcessInstanceIndex.ENDED_BY).property("startedDate", ElementType.METHOD).field() .name(ProcessInstanceIndex.STARTED_DATE).index(Index.UN_TOKENIZED) .dateBridge(Resolution.MILLISECOND).property("endedDate", ElementType.METHOD).field() .name(ProcessInstanceIndex.ENDED_DATE).index(Index.UN_TOKENIZED) .dateBridge(Resolution.MILLISECOND).property("lastUpdate", ElementType.METHOD).field() .name(ProcessInstanceIndex.LAST_UPDATE).index(Index.UN_TOKENIZED) .dateBridge(Resolution.MILLISECOND).entity(RuntimeRecordImpl.class) .property("processDefinitionUUID", ElementType.METHOD).field() .name(ProcessInstanceIndex.PROCESS_DEFINITION_UUID).bridge(UUIDFieldBridge.class) .property("processInstanceUUID", ElementType.METHOD).field() .name(ProcessInstanceIndex.PROCESS_INSTANCE_UUID).bridge(UUIDFieldBridge.class) .property("rootInstanceUUID", ElementType.METHOD).field() .name(ProcessInstanceIndex.PROCESS_ROOT_INSTANCE_UUID).bridge(UUIDFieldBridge.class) .entity(CommentImpl.class).indexed().indexName("comment").property("dbid", ElementType.FIELD) .documentId().name(CommentIndex.DBID).entity(Comment.class) .property("message", ElementType.METHOD).field().name(CommentIndex.MESSAGE) .property("userId", ElementType.METHOD).field().name(CommentIndex.AUTHOR) .property("date", ElementType.METHOD).field().name(CommentIndex.DATE).index(Index.UN_TOKENIZED) .dateBridge(Resolution.MILLISECOND) .entity(InternalActivityInstance.class).indexed().indexName("activity_instance") .property("dbid", ElementType.FIELD).documentId().name(ActivityInstanceIndex.DBID) .entity(TaskInstance.class).property("taskCandidates", ElementType.METHOD).field() .name(ActivityInstanceIndex.CANDIDATE).bridge(StringSetFieldBridge.class) .entity(ActivityInstanceImpl.class).property("taskCandidates", ElementType.METHOD).field() .name(ActivityInstanceIndex.CANDIDATE).bridge(StringSetFieldBridge.class) .property("lastKnownVariableValues", ElementType.METHOD).field().name("variable") .bridge(ObjectMapFieldBridge.class).entity(LightActivityInstanceImpl.class) .property("activityName", ElementType.METHOD).field().name(ActivityInstanceIndex.NAME) .property("state", ElementType.METHOD).field().name(ActivityInstanceIndex.STATE) .property("priority", ElementType.METHOD).field().name(ActivityInstanceIndex.PRIORITY) .index(Index.UN_TOKENIZED).property("lastUpdate", ElementType.METHOD).field() .name(ActivityInstanceIndex.LAST_UPDATE).index(Index.UN_TOKENIZED) .dateBridge(Resolution.MILLISECOND).property("expectedEndDate", ElementType.METHOD).field() .name(ActivityInstanceIndex.EXPECTED_END_DATE).index(Index.UN_TOKENIZED) .dateBridge(Resolution.MILLISECOND).entity(ActivityInstance.class) .property("activityName", ElementType.METHOD).field().name(ActivityInstanceIndex.NAME) .property("state", ElementType.METHOD).field().name(ActivityInstanceIndex.STATE) .property("lastKnownVariableValues", ElementType.METHOD).field().name("variable") .bridge(ObjectMapFieldBridge.class).entity(LightActivityInstance.class) .property("activityDescription", ElementType.METHOD).field() .name(ActivityInstanceIndex.DESCRIPTION).property("priority", ElementType.METHOD).field() .name(ActivityInstanceIndex.PRIORITY).index(Index.UN_TOKENIZED) .property("lastUpdate", ElementType.METHOD).field().name(ActivityInstanceIndex.LAST_UPDATE) .index(Index.UN_TOKENIZED).dateBridge(Resolution.MILLISECOND) .property("expectedEndDate", ElementType.METHOD).field() .name(ActivityInstanceIndex.EXPECTED_END_DATE).index(Index.UN_TOKENIZED) .dateBridge(Resolution.MILLISECOND) .entity(UserImpl.class).indexed().indexName("user").property("dbid", ElementType.FIELD) .documentId().name(UserIndex.DBID).property("username", ElementType.FIELD).field() .name(UserIndex.NAME).property("firstName", ElementType.FIELD).field() .name(UserIndex.FIRST_NAME).property("lastName", ElementType.FIELD).field() .name(UserIndex.LAST_NAME).property("manager", ElementType.FIELD).field() .name(UserIndex.MANAGER).property("delegate", ElementType.FIELD).field() .name(UserIndex.DELEGATE).property("title", ElementType.FIELD).field().name(UserIndex.TITLE) .property("jobTitle", ElementType.FIELD).field().name(UserIndex.JOB_TITLE) .property("professionalContactInfo", ElementType.FIELD).indexEmbedded() .property("personalContactInfo", ElementType.FIELD).indexEmbedded().entity(ContactInfo.class) .property("email", ElementType.METHOD).field().name(ContactInfoIndex.EMAIL) .property("phoneNumber", ElementType.METHOD).field().name(ContactInfoIndex.PHONE_NUMBER) .property("faxNumber", ElementType.METHOD).field().name(ContactInfoIndex.FAX_NUMBER) .property("building", ElementType.METHOD).field().name(ContactInfoIndex.BUILDING) .property("room", ElementType.METHOD).field().name(ContactInfoIndex.ROOM) .property("address", ElementType.METHOD).field().name(ContactInfoIndex.ADDRESS) .property("zipCode", ElementType.METHOD).field().name(ContactInfoIndex.ZIP_CODE) .property("city", ElementType.METHOD).field().name(ContactInfoIndex.CITY) .property("state", ElementType.METHOD).field().name(ContactInfoIndex.STATE) .property("country", ElementType.METHOD).field().name(ContactInfoIndex.COUNTRY) .property("website", ElementType.METHOD).field().name(ContactInfoIndex.WEBSITE) .entity(RoleImpl.class).indexed().indexName("role").property("dbid", ElementType.FIELD) .documentId().name(RoleIndex.DBID).property("name", ElementType.FIELD).field() .name(RoleIndex.NAME).property("label", ElementType.FIELD).field().name(RoleIndex.LABEL) .entity(GroupImpl.class).indexed().indexName("group").property("dbid", ElementType.FIELD) .documentId().name(GroupIndex.DBID).property("name", ElementType.METHOD).field() .name(GroupIndex.NAME).property("label", ElementType.METHOD).field().name(GroupIndex.LABEL) .entity(CaseImpl.class).indexed().indexName("case").property("dbid", ElementType.FIELD) .documentId().name(CaseIndex.DBID).property("labelName", ElementType.FIELD).field() .name(CaseIndex.LABEL_NAME).property("ownerName", ElementType.FIELD).field() .name(CaseIndex.OWNER_NAME).property("uuid", ElementType.FIELD).field() .name(CaseIndex.PROCESS_INSTANCE_UUID).bridge(UUIDFieldBridge.class); configuration.getProperties().put(Environment.MODEL_MAPPING, mapping); configuration.setProperty("hibernate.search.default.directory_provider", FSDirectoryProvider.class.getName()); String path = getDefaultIndexesDirectorPath(configuration); configuration.setProperty("hibernate.search.default.indexBase", path); configuration.setProperty("hibernate.search.autoregister_listeners", "false"); String fullTextIndexListener = FullTextIndexEventListener.class.getName(); configuration.setListener("post-update", fullTextIndexListener); configuration.setListener("post-insert", fullTextIndexListener); configuration.setListener("post-delete", fullTextIndexListener); configuration.setListener("post-collection-recreate", fullTextIndexListener); configuration.setListener("post-collection-remove", fullTextIndexListener); configuration.setListener("post-collection-update", fullTextIndexListener); String[] listeners = new String[] { DefaultFlushEventListener.class.getName(), fullTextIndexListener }; configuration.setListeners("flush", listeners); } }