List of usage examples for org.hibernate.cfg Configuration configure
@Deprecated public Configuration configure(org.w3c.dom.Document document) throws HibernateException
From source file:hibernatePersistence.util.HibernateUtil.java
private static SessionFactory buildSessionFactory() { try {/* w w w. j ava 2 s. c o m*/ Configuration cfg = new Configuration(); cfg.configure("hibernate.cfg.xml"); return cfg.buildSessionFactory(); } catch (Throwable e) { System.out.println("Erro:" + e); throw new ExceptionInInitializerError(e); } // return null; }
From source file:id.qwack.configuration.HibernateUtil.java
private static SessionFactory buildSessionFactory() { try {/*from w ww . j av a 2s. c om*/ // Create the SessionFactory from hibernate.cfg.xml Configuration configuration = new Configuration(); configuration.configure("hibernate.cfg.xml"); //System.out.println("Hibernate Configuration loaded"); ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder() .applySettings(configuration.getProperties()).build(); //System.out.println("Hibernate serviceRegistry created"); SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry); return sessionFactory; } catch (Throwable ex) { System.err.println("Initial SessionFactory creation failed." + ex); ex.printStackTrace(); throw new ExceptionInInitializerError(ex); } }
From source file:io.heming.accountbook.facade.FacadeUtil.java
License:Apache License
private static SessionFactory buildSessionFactory() { try {/*from w w w.jav a 2s. c o m*/ // Create the SessionFactory from hibernate.cfg.xml Configuration conf = new Configuration(); conf.configure("hibernate.cfg.xml"); ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder() .applySettings(conf.getProperties()).build(); SessionFactory sessionFactory = conf.buildSessionFactory(serviceRegistry); return sessionFactory; } 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:it.doqui.index.ecmengine.business.personalization.hibernate.RoutingLocalSessionFactoryBean.java
License:Open Source License
protected SessionFactory buildSessionFactory() throws Exception { logger.debug("[RoutingLocalSessionFactoryBean::buildSessionFactory] BEGIN"); SessionFactory sf = null;//from w w w .j av a2s. c o m // Create Configuration instance. Configuration config = newConfiguration(); DataSource currentDataSource = getCurrentDataSource(); logger.debug("[RoutingLocalSessionFactoryBean::buildSessionFactory] " + "Repository '" + RepositoryManager.getCurrentRepository() + "' -- Got currentDataSource: " + currentDataSource); if (currentDataSource == null) { throw new IllegalStateException("Null DataSource!"); } // Make given DataSource available for SessionFactory configuration. logger.debug("[RoutingLocalSessionFactoryBean::buildSessionFactory] " + "Thread '" + Thread.currentThread().getName() + "' -- Setting DataSource for current thread: " + currentDataSource); CONFIG_TIME_DS_HOLDER.set(currentDataSource); if (this.jtaTransactionManager != null) { // Make Spring-provided JTA TransactionManager available. CONFIG_TIME_TM_HOLDER.set(this.jtaTransactionManager); } if (this.lobHandler != null) { // Make given LobHandler available for SessionFactory configuration. // Do early because because mapping resource might refer to custom types. CONFIG_TIME_LOB_HANDLER_HOLDER.set(this.lobHandler); } try { // Set connection release mode "on_close" as default. // This was the case for Hibernate 3.0; Hibernate 3.1 changed // it to "auto" (i.e. "after_statement" or "after_transaction"). // However, for Spring's resource management (in particular for // HibernateTransactionManager), "on_close" is the better default. config.setProperty(Environment.RELEASE_CONNECTIONS, ConnectionReleaseMode.ON_CLOSE.toString()); if (!isExposeTransactionAwareSessionFactory()) { // Not exposing a SessionFactory proxy with transaction-aware // getCurrentSession() method -> set Hibernate 3.1 CurrentSessionContext // implementation instead, providing the Spring-managed Session that way. // Can be overridden by a custom value for corresponding Hibernate property. config.setProperty(Environment.CURRENT_SESSION_CONTEXT_CLASS, "org.springframework.orm.hibernate3.SpringSessionContext"); } 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.typeDefinitions != null) { // Register specified Hibernate type definitions. Mappings mappings = config.createMappings(); for (int i = 0; i < this.typeDefinitions.length; i++) { TypeDefinitionBean typeDef = this.typeDefinitions[i]; mappings.addTypeDef(typeDef.getTypeName(), typeDef.getTypeClass(), typeDef.getParameters()); } } if (this.filterDefinitions != null) { // Register specified Hibernate FilterDefinitions. for (int i = 0; i < this.filterDefinitions.length; i++) { config.addFilterDefinition(this.filterDefinitions[i]); } } if (this.configLocations != null) { for (int i = 0; i < this.configLocations.length; i++) { // Load Hibernate configuration from given location. config.configure(this.configLocations[i].getURL()); } } if (this.hibernateProperties != null) { // Add given Hibernate properties to Configuration. config.addProperties(this.hibernateProperties); } if (currentDataSource != null) { boolean actuallyTransactionAware = (this.useTransactionAwareDataSource || currentDataSource instanceof TransactionAwareDataSourceProxy); // Set Spring-provided DataSource as Hibernate ConnectionProvider. config.setProperty(Environment.CONNECTION_PROVIDER, actuallyTransactionAware ? TransactionAwareDataSourceConnectionProvider.class.getName() : RoutingLocalDataSourceConnectionProvider.class.getName()); } if (this.jtaTransactionManager != null) { // Set Spring-provided JTA TransactionManager as Hibernate property. config.setProperty(Environment.TRANSACTION_MANAGER_STRATEGY, LocalTransactionManagerLookup.class.getName()); } if (this.mappingLocations != null) { // Register given Hibernate mapping definitions, contained in resource files. for (int i = 0; i < this.mappingLocations.length; i++) { config.addInputStream(this.mappingLocations[i].getInputStream()); } } if (this.cacheableMappingLocations != null) { // Register given cacheable Hibernate mapping definitions, read from the file system. for (int i = 0; i < this.cacheableMappingLocations.length; i++) { config.addCacheableFile(this.cacheableMappingLocations[i].getFile()); } } if (this.mappingJarLocations != null) { // Register given Hibernate mapping definitions, contained in jar files. for (int i = 0; i < this.mappingJarLocations.length; i++) { Resource resource = this.mappingJarLocations[i]; config.addJar(resource.getFile()); } } if (this.mappingDirectoryLocations != null) { // Register all Hibernate mapping definitions in the given directories. for (int i = 0; i < this.mappingDirectoryLocations.length; i++) { File file = this.mappingDirectoryLocations[i].getFile(); if (!file.isDirectory()) { throw new IllegalArgumentException("Mapping directory location [" + this.mappingDirectoryLocations[i] + "] does not denote a directory"); } config.addDirectory(file); } } 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 = StringUtils .commaDelimitedListToStringArray(this.entityCacheStrategies.getProperty(className)); if (strategyAndRegion.length > 1) { config.setCacheConcurrencyStrategy(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 = StringUtils .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<?, ?> entry : this.eventListeners.entrySet()) { Assert.isTrue(entry.getKey() instanceof String, "Event listener key needs to be of type String"); String listenerType = (String) entry.getKey(); Object listenerObject = entry.getValue(); if (listenerObject instanceof Collection) { Collection<?> listeners = (Collection<?>) 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.debug( "[RoutingLocalSessionFactoryBean::buildSessionFactory] Building new Hibernate SessionFactory."); this.configuration = config; SessionFactoryProxy sessionFactoryProxy = new SessionFactoryProxy( repositoryManager.getDefaultRepository().getId()); for (Repository repository : repositoryManager.getRepositories()) { logger.debug("[RoutingLocalSessionFactoryBean::buildSessionFactory] " + "Repository '" + repository.getId() + "' -- Building SessionFactory..."); RepositoryManager.setCurrentRepository(repository.getId()); sessionFactoryProxy.addSessionFactory(repository.getId(), newSessionFactory(config)); } RepositoryManager.setCurrentRepository(repositoryManager.getDefaultRepository().getId()); sf = sessionFactoryProxy; } finally { if (currentDataSource != null) { // Reset DataSource holder. CONFIG_TIME_DS_HOLDER.set(null); } if (this.jtaTransactionManager != null) { // Reset TransactionManager holder. CONFIG_TIME_TM_HOLDER.set(null); } if (this.lobHandler != null) { // Reset LobHandler holder. CONFIG_TIME_LOB_HANDLER_HOLDER.set(null); } } // Execute schema update if requested. if (this.schemaUpdate) { updateDatabaseSchema(); } return sf; }
From source file:it.eng.spagobi.tools.importexport.ExportUtilities.java
License:Mozilla Public License
/** * Creates an Hibernate session factory for the export database. * /*from ww w . ja v a 2 s .co m*/ * @param pathDBFolder Path of the export database folder * * @return The Hibernate Session Factory * * @throws EMFUserError the EMF user error */ public static SessionFactory getHibSessionExportDB(String pathDBFolder) throws EMFUserError { logger.debug("IN"); Configuration conf = new Configuration(); String resource = "it/eng/spagobi/tools/importexport/metadata/hibernate.cfg.hsql.export.xml"; conf = conf.configure(resource); String hsqlJdbcString = "jdbc:hsqldb:file:" + pathDBFolder + "/metadata;shutdown=true"; conf.setProperty("hibernate.connection.url", hsqlJdbcString); SessionFactory sessionFactory = conf.buildSessionFactory(); logger.debug("OUT"); return sessionFactory; }
From source file:it.eng.spagobi.tools.importexport.ImportUtilities.java
License:Mozilla Public License
/** * Creates an Hibernate session factory for the exported database. * //from w w w. jav a2 s . c o m * @param pathDBFolder The path of the folder which contains the exported database * * @return The Hibernate session factory * * @throws EMFUserError the EMF user error */ public static SessionFactory getHibSessionExportDB(String pathDBFolder) throws EMFUserError { logger.debug("IN"); Configuration conf = new Configuration(); String resource = "it/eng/spagobi/tools/importexport/metadata/hibernate.cfg.hsql.export.xml"; conf = conf.configure(resource); String hsqlJdbcString = "jdbc:hsqldb:file:" + pathDBFolder + "/metadata;shutdown=true"; conf.setProperty("hibernate.connection.url", hsqlJdbcString); SessionFactory sessionFactory = conf.buildSessionFactory(); logger.debug("IN"); return sessionFactory; }
From source file:javahibernate2.JavaHibernate2.java
public SessionFactory initHibernate() { try {//from ww w.j av a 2 s.com final Configuration config = new Configuration(); config.configure("hibernate.cfg.xml"); LOG.info("Connection to hibernate URL = " + config.getProperty("hibernate.connection.url")); StandardServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder() .applySettings(config.getProperties()).build(); return config.buildSessionFactory(serviceRegistry); } catch (Exception e) { System.out.println(e.toString()); return null; } }
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 w w w . j av a2 s.co 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.Contexto.ContextoBase.java
public ContextoBase(String NombreConf) { Configuration conf = new Configuration(); conf.configure(NombreConf); ServiceRegistryBuilder srBuilder = new ServiceRegistryBuilder(); srBuilder.applySettings(conf.getProperties()); ServiceRegistry sr = srBuilder.build(); this.factory = conf.buildSessionFactory(sr); }
From source file:mainclass.MainUser.java
public static void main(String h[]) { Configuration config = new Configuration(); config.configure("hibernate.cfg.xml"); SessionFactory factory = config.buildSessionFactory(); Session session = factory.openSession(); Transaction tx = session.beginTransaction(); UserDetail user = (UserDetail) session.get(UserDetail.class, 3); // user.setUname("new user"); session.delete(user);// w w w . j a va 2 s. c o m tx.commit(); session.close(); }