org.hibernate.cfg.Configuration Java Examples
The following examples show how to use
org.hibernate.cfg.Configuration.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: InHibernate.java From Transwarp-Sample-Code with MIT License | 8 votes |
public static void main(String[] args) { String path = "hibernate.cfg.xml"; Configuration cfg = new Configuration().configure(path); SessionFactory sessionFactory = cfg.buildSessionFactory(); Session session = sessionFactory.openSession(); session.beginTransaction(); User user = new User(); user.setId("443"); user.setName("baa"); session.save(user); // session.close(); session.getTransaction().commit(); sessionFactory.close(); }
Example #2
Source File: ExtendsTest.java From cacheonix-core with GNU Lesser General Public License v2.1 | 6 votes |
public void testMissingSuper() { Configuration cfg = new Configuration(); try { cfg.addResource( getBaseForMappings() + "extendshbm/Customer.hbm.xml" ); assertNull( "cannot be in the configuration yet!", cfg.getClassMapping( "org.hibernate.test.extendshbm.Customer" ) ); cfg.addResource( getBaseForMappings() + "extendshbm/Employee.hbm.xml" ); cfg.buildSessionFactory(); fail( "Should not be able to build sessionfactory without a Person" ); } catch ( HibernateException e ) { } }
Example #3
Source File: ReadWriteTest.java From redisson with Apache License 2.0 | 6 votes |
@Override protected void configure(Configuration cfg) { super.configure(cfg); cfg.setProperty(Environment.DRIVER, org.h2.Driver.class.getName()); cfg.setProperty(Environment.URL, "jdbc:h2:mem:db1;DB_CLOSE_DELAY=-1;"); cfg.setProperty(Environment.USER, "sa"); cfg.setProperty(Environment.PASS, ""); cfg.setProperty(Environment.CACHE_REGION_PREFIX, ""); cfg.setProperty(Environment.GENERATE_STATISTICS, "true"); cfg.setProperty(Environment.USE_SECOND_LEVEL_CACHE, "true"); cfg.setProperty(Environment.USE_QUERY_CACHE, "true"); cfg.setProperty(Environment.CACHE_REGION_FACTORY, RedissonRegionFactory.class.getName()); cfg.setProperty("hibernate.cache.redisson.item.eviction.max_entries", "100"); cfg.setProperty("hibernate.cache.redisson.item.expiration.time_to_live", "1500"); cfg.setProperty("hibernate.cache.redisson.item.expiration.max_idle_time", "1000"); }
Example #4
Source File: HibernateDataSource.java From Knowage-Server with GNU Affero General Public License v3.0 | 6 votes |
protected void addDatamart(FileDataSourceConfiguration configuration, boolean extendClassLoader) { Configuration cfg = null; SessionFactory sf = null; if(configuration.getFile() == null) return; cfg = buildEmptyConfiguration(); configurationMap.put(configuration.getModelName(), cfg); if (extendClassLoader){ updateCurrentClassLoader(configuration.getFile()); } cfg.addJar(configuration.getFile()); try { compositeHibernateConfiguration.addJar(configuration.getFile()); } catch (Throwable t) { throw new RuntimeException("Cannot add datamart", t); } sf = cfg.buildSessionFactory(); sessionFactoryMap.put(configuration.getModelName(), sf); }
Example #5
Source File: HibernateUtil.java From yeti with MIT License | 6 votes |
private static SessionFactory buildSessionAnnotationFactory() { try { Properties dbProps = ConfigSettings.getDatabaseProperties(); Configuration configuration = new Configuration(); configuration.setProperties(dbProps); configuration.configure("hibernate-annotation.cfg.xml"); ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build(); sessionFactory = configuration.buildSessionFactory(serviceRegistry); return sessionFactory; } catch (HibernateException ex) { Logger.getLogger(HibernateUtil.class.getName()).log(Level.SEVERE, null, ex); throw new ExceptionInInitializerError(ex); } }
Example #6
Source File: CacheHibernateStoreSessionListenerSelfTest.java From ignite with Apache License 2.0 | 6 votes |
/** {@inheritDoc} */ @Override protected Factory<CacheStoreSessionListener> sessionListenerFactory() { return new Factory<CacheStoreSessionListener>() { @Override public CacheStoreSessionListener create() { CacheHibernateStoreSessionListener lsnr = new CacheHibernateStoreSessionListener(); SessionFactory sesFactory = new Configuration(). setProperty("hibernate.connection.url", URL). addAnnotatedClass(Table1.class). addAnnotatedClass(Table2.class). buildSessionFactory(); lsnr.setSessionFactory(sesFactory); return lsnr; } }; }
Example #7
Source File: ExtendsTest.java From cacheonix-core with GNU Lesser General Public License v2.1 | 6 votes |
public void testJoinedSubclassAndEntityNamesOnly() { Configuration cfg = new Configuration(); try { cfg.addResource( getBaseForMappings() + "extendshbm/entitynames.hbm.xml" ); cfg.buildMappings(); assertNotNull( cfg.getClassMapping( "EntityHasName" ) ); assertNotNull( cfg.getClassMapping( "EntityCompany" ) ); } catch ( HibernateException e ) { e.printStackTrace(); fail( "should not fail with exception! " + e ); } }
Example #8
Source File: ITCaseDailyStatHsqldbSchema.java From olat with Apache License 2.0 | 6 votes |
@Override protected void setUp() throws Exception { final Configuration config = new Configuration().setProperty("hibernate.dialect", "org.hibernate.dialect.HSQLDialect") .setProperty("hibernate.connection.driver_class", "org.hsqldb.jdbcDriver").setProperty("hibernate.connection.url", "jdbc:hsqldb:mem:baseball") .setProperty("hibernate.connection.username", "sa").setProperty("hibernate.connection.password", "").setProperty("hibernate.connection.pool_size", "1") .setProperty("hibernate.connection.autocommit", "true").setProperty("hibernate.cache.provider_class", "org.hibernate.cache.HashtableCacheProvider") .setProperty("hibernate.hbm2ddl.auto", "create-drop").setProperty("hibernate.show_sql", "true").addClass(DailyStat.class); HibernateUtil.setSessionFactory(config.buildSessionFactory()); // uncomment the following if you want to launch a the dbmanager gui (while debugging through this class probably) /* * Runnable r = new Runnable() { * * @Override public void run() { org.hsqldb.util.DatabaseManagerSwing.main(new String[0]); } }; Thread th = new Thread(r); th.setDaemon(true); th.start(); */}
Example #9
Source File: HibernateUtil.java From journaldev with MIT License | 6 votes |
private static SessionFactory buildSessionFactory() { try { // 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); } }
Example #10
Source File: BaseCoreFunctionalTestCase.java From google-cloud-spanner-hibernate with GNU Lesser General Public License v2.1 | 6 votes |
protected void rebuildSessionFactory(Consumer<Configuration> configurationAdapter) { if ( sessionFactory == null ) { return; } try { sessionFactory.close(); sessionFactory = null; configuration = null; serviceRegistry.destroy(); serviceRegistry = null; } catch (Exception ignore) { } buildSessionFactory( configurationAdapter ); }
Example #11
Source File: BaseCoreFunctionalTestCase.java From google-cloud-spanner-hibernate with GNU Lesser General Public License v2.1 | 6 votes |
protected Configuration constructConfiguration() { Configuration configuration = new Configuration(); configuration.setProperty( AvailableSettings.CACHE_REGION_FACTORY, CachingRegionFactory.class.getName() ); configuration.setProperty( AvailableSettings.USE_NEW_ID_GENERATOR_MAPPINGS, "true" ); if ( createSchema() ) { configuration.setProperty( Environment.HBM2DDL_AUTO, "update" ); final String secondSchemaName = createSecondSchema(); if ( StringHelper.isNotEmpty( secondSchemaName ) ) { if ( !( getDialect() instanceof H2Dialect ) ) { throw new UnsupportedOperationException( "Only H2 dialect supports creation of second schema." ); } Helper.createH2Schema( secondSchemaName, configuration ); } } configuration.setImplicitNamingStrategy( ImplicitNamingStrategyLegacyJpaImpl.INSTANCE ); configuration.setProperty( Environment.DIALECT, getDialect().getClass().getName() ); return configuration; }
Example #12
Source File: HibernateUtil.java From serverless with Apache License 2.0 | 6 votes |
public static SessionFactory getSessionFactory() { if (null != sessionFactory) return sessionFactory; Configuration configuration = new Configuration(); String jdbcUrl = "jdbc:mysql://" + System.getenv("RDS_HOSTNAME") + "/" + System.getenv("RDS_DB_NAME"); configuration.setProperty("hibernate.connection.url", jdbcUrl); configuration.setProperty("hibernate.connection.username", System.getenv("RDS_USERNAME")); configuration.setProperty("hibernate.connection.password", System.getenv("RDS_PASSWORD")); configuration.configure(); ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build(); try { sessionFactory = configuration.buildSessionFactory(serviceRegistry); } catch (HibernateException e) { System.err.println("Initial SessionFactory creation failed." + e); throw new ExceptionInInitializerError(e); } return sessionFactory; }
Example #13
Source File: LocalSessionFactoryBeanTests.java From spring4-understanding with Apache License 2.0 | 6 votes |
@Test public void testLocalSessionFactoryBeanWithCustomSessionFactory() throws Exception { final SessionFactory sessionFactory = mock(SessionFactory.class); LocalSessionFactoryBean sfb = new LocalSessionFactoryBean() { @Override protected SessionFactory newSessionFactory(Configuration config) { return sessionFactory; } }; sfb.setMappingResources(new String[0]); sfb.setDataSource(new DriverManagerDataSource()); sfb.setExposeTransactionAwareSessionFactory(false); sfb.afterPropertiesSet(); assertTrue(sessionFactory == sfb.getObject()); sfb.destroy(); verify(sessionFactory).close(); }
Example #14
Source File: MigrationTest.java From cacheonix-core with GNU Lesser General Public License v2.1 | 6 votes |
public void testSimpleColumnAddition() { String resource1 = "org/hibernate/test/schemaupdate/1_Version.hbm.xml"; String resource2 = "org/hibernate/test/schemaupdate/2_Version.hbm.xml"; Configuration v1cfg = new Configuration(); v1cfg.addResource( resource1 ); new SchemaExport( v1cfg ).execute( false, true, true, false ); SchemaUpdate v1schemaUpdate = new SchemaUpdate( v1cfg ); v1schemaUpdate.execute( true, true ); assertEquals( 0, v1schemaUpdate.getExceptions().size() ); Configuration v2cfg = new Configuration(); v2cfg.addResource( resource2 ); SchemaUpdate v2schemaUpdate = new SchemaUpdate( v2cfg ); v2schemaUpdate.execute( true, true ); assertEquals( 0, v2schemaUpdate.getExceptions().size() ); }
Example #15
Source File: WikiHibernateUtil.java From dkpro-jwpl with Apache License 2.0 | 6 votes |
public static SessionFactory getSessionFactory(DatabaseConfiguration config) { if (config.getLanguage() == null) { throw new ExceptionInInitializerError("Database configuration error. 'Language' is empty."); } else if (config.getHost() == null) { throw new ExceptionInInitializerError("Database configuration error. 'Host' is empty."); } else if (config.getDatabase() == null) { throw new ExceptionInInitializerError("Database configuration error. 'Database' is empty."); } String uniqueSessionKey = config.getLanguage().toString() + config.getHost() + config.getDatabase(); if (!sessionFactoryMap.containsKey(uniqueSessionKey)) { Configuration configuration = getConfiguration(config); StandardServiceRegistryBuilder ssrb = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()); SessionFactory sessionFactory = configuration.buildSessionFactory(ssrb.build()); sessionFactoryMap.put(uniqueSessionKey, sessionFactory); } return sessionFactoryMap.get(uniqueSessionKey); }
Example #16
Source File: LocalSessionFactoryBeanTests.java From spring4-understanding with Apache License 2.0 | 5 votes |
@Test @SuppressWarnings("serial") public void testLocalSessionFactoryBeanWithEntityInterceptor() throws Exception { LocalSessionFactoryBean sfb = new LocalSessionFactoryBean() { @Override protected Configuration newConfiguration() { return new Configuration() { @Override public Configuration setInterceptor(Interceptor interceptor) { throw new IllegalArgumentException(interceptor.toString()); } }; } }; sfb.setMappingResources(new String[0]); sfb.setDataSource(new DriverManagerDataSource()); Interceptor entityInterceptor = mock(Interceptor.class); sfb.setEntityInterceptor(entityInterceptor); try { sfb.afterPropertiesSet(); fail("Should have thrown IllegalArgumentException"); } catch (IllegalArgumentException ex) { // expected assertTrue("Correct exception", ex.getMessage().equals(entityInterceptor.toString())); } }
Example #17
Source File: OLATLocalSessionFactoryBean.java From olat with Apache License 2.0 | 5 votes |
@Override protected void postProcessMappings(Configuration config) throws HibernateException { try { if (additionalDBMappings != null && additionalDBMappings.length > 0) { for (AdditionalDBMappings addMapping : additionalDBMappings) { List<String> xmlFiles = addMapping.getXmlFiles(); if (xmlFiles != null) { for (String mapping : xmlFiles) { // we cannot access the classloader magic used by the LocalSessionFactoryBean Resource resource = new ClassPathResource(mapping.trim()); config.addInputStream(resource.getInputStream()); } } List<Class<?>> annotatedClasses = addMapping.getAnnotatedClasses(); if (annotatedClasses != null) { for (Class<?> annotatedClass : annotatedClasses) { config.addClass(annotatedClass); } } } } super.postProcessMappings(config); } catch (Exception e) { log.error("Error during the post processing of the hibernate session factory.", e); } }
Example #18
Source File: AggressiveReleaseTest.java From cacheonix-core with GNU Lesser General Public License v2.1 | 5 votes |
public void configure(Configuration cfg) { super.configure( cfg ); cfg.setProperty( Environment.RELEASE_CONNECTIONS, ConnectionReleaseMode.AFTER_STATEMENT.toString() ); cfg.setProperty( Environment.CONNECTION_PROVIDER, DummyConnectionProvider.class.getName() ); cfg.setProperty( Environment.TRANSACTION_STRATEGY, CMTTransactionFactory.class.getName() ); cfg.setProperty( Environment.TRANSACTION_MANAGER_STRATEGY, DummyTransactionManagerLookup.class.getName() ); cfg.setProperty( Environment.GENERATE_STATISTICS, "true" ); cfg.setProperty( Environment.STATEMENT_BATCH_SIZE, "0" ); }
Example #19
Source File: SecondaryTableTest.java From hibernate-reactive with GNU Lesser General Public License v2.1 | 5 votes |
@Override protected Configuration constructConfiguration() { Configuration configuration = super.constructConfiguration(); configuration.addAnnotatedClass( SecondaryTableTest.Book.class ); configuration.addAnnotatedClass( SecondaryTableTest.Author.class ); return configuration; }
Example #20
Source File: AbstractCachingDemo.java From hibernate-demos with Apache License 2.0 | 5 votes |
protected AbstractCachingDemo() { final Configuration configuration = new Configuration(); configuration.addAnnotatedClass( Project.class ); configuration.addAnnotatedClass( User.class ); configuration.addAnnotatedClass( Skill.class ); sessionFactory = configuration.buildSessionFactory( new StandardServiceRegistryBuilder().build() ); }
Example #21
Source File: LazyPropertyTest.java From hibernate-reactive with GNU Lesser General Public License v2.1 | 5 votes |
@Override protected Configuration constructConfiguration() { Configuration configuration = super.constructConfiguration(); configuration.addAnnotatedClass( Book.class ); configuration.addAnnotatedClass( Author.class ); return configuration; }
Example #22
Source File: HibernateUtil.java From Quelea with GNU General Public License v3.0 | 5 votes |
public static boolean init() { try { LOGGER.info("Initialising hibernate"); final String location = new File(new File(QueleaProperties.get().getQueleaUserHome(), "database_new"), "database_new").getAbsolutePath(); final Configuration cfg = new Configuration(); cfg.setProperty("hibernate.connection.url", "jdbc:hsqldb:" + location); cfg.setProperty("hibernate.connection.dialect", "org.hibernate.dialect.HSQLDialect"); cfg.setProperty("hibernate.connection.driver_class", "org.hsqldb.jdbcDriver"); cfg.setProperty("hibernate.show_sql", "false"); cfg.setProperty("hibernate.hbm2ddl.auto", "update"); cfg.setProperty("hibernate.implicit_naming_strategy", "legacy-hbm"); cfg.setProperty("hibernate.connection.characterEncoding", "utf8"); // cfg.setImplicitNamingStrategy(new EJB3ImplicitNamingStrategy()); cfg.addAnnotatedClass(org.quelea.data.db.model.Song.class); cfg.addAnnotatedClass(org.quelea.data.db.model.Theme.class); cfg.addAnnotatedClass(org.quelea.data.db.model.TextShadow.class); LOGGER.info("Initialised hibernate properties"); serviceRegistry = new StandardServiceRegistryBuilder().applySettings(cfg.getProperties()).build(); LOGGER.info("Initialised hibernate service registry"); sessionFactory = cfg.buildSessionFactory(serviceRegistry); LOGGER.info("Initialised hibernate session factory"); init = true; return true; } catch (Throwable ex) { LOGGER.log(Level.INFO, "Initial SessionFactory creation failed. Quelea is probably already running.", ex); return false; } }
Example #23
Source File: SchedulerDBManager.java From scheduling with GNU Affero General Public License v3.0 | 5 votes |
public static SchedulerDBManager createInMemorySchedulerDBManager() { Configuration config = new Configuration(); config.setProperty("hibernate.connection.driver_class", "org.hsqldb.jdbc.JDBCDriver"); config.setProperty("hibernate.connection.url", "jdbc:hsqldb:mem:" + System.currentTimeMillis() + ";hsqldb.tx=mvcc"); config.setProperty("hibernate.dialect", "org.hibernate.dialect.HSQLDialect"); return new SchedulerDBManager(config, true); }
Example #24
Source File: HibernateExceptionUnitTest.java From tutorials with MIT License | 5 votes |
@Test public void givenMissingTable_whenEntitySaved_thenSQLGrammarException() { thrown.expect(isA(PersistenceException.class)); thrown.expectCause(isA(SQLGrammarException.class)); thrown .expectMessage("SQLGrammarException: could not prepare statement"); Configuration cfg = getConfiguration(); cfg.addAnnotatedClass(Product.class); SessionFactory sessionFactory = cfg.buildSessionFactory(); Session session = null; Transaction transaction = null; try { session = sessionFactory.openSession(); transaction = session.beginTransaction(); Product product = new Product(); product.setId(1); product.setName("Product 1"); session.save(product); transaction.commit(); } catch (Exception e) { rollbackTransactionQuietly(transaction); throw (e); } finally { closeSessionQuietly(session); closeSessionFactoryQuietly(sessionFactory); } }
Example #25
Source File: CMTTest.java From cacheonix-core with GNU Lesser General Public License v2.1 | 5 votes |
public void configure(Configuration cfg) { cfg.setProperty( Environment.CONNECTION_PROVIDER, DummyConnectionProvider.class.getName() ); cfg.setProperty( Environment.TRANSACTION_MANAGER_STRATEGY, DummyTransactionManagerLookup.class.getName() ); cfg.setProperty( Environment.TRANSACTION_STRATEGY, CMTTransactionFactory.class.getName() ); cfg.setProperty( Environment.AUTO_CLOSE_SESSION, "true" ); cfg.setProperty( Environment.FLUSH_BEFORE_COMPLETION, "true" ); cfg.setProperty( Environment.RELEASE_CONNECTIONS, ConnectionReleaseMode.AFTER_STATEMENT.toString() ); cfg.setProperty( Environment.GENERATE_STATISTICS, "true" ); cfg.setProperty( Environment.USE_QUERY_CACHE, "true" ); cfg.setProperty( Environment.DEFAULT_ENTITY_MODE, EntityMode.MAP.toString() ); }
Example #26
Source File: SFLocalContext.java From sailfish-core with Apache License 2.0 | 5 votes |
private void tryToMigrate(Configuration configuration, Session session) throws Exception { try { UnlimitedMessageColumnsMigration migration = new UnlimitedMessageColumnsMigration(session, configuration); migration.migrate(); } catch (Exception e) { logger.error("Could not migrate database to set unlimited raw/json/human message columns.", e); throw e; } }
Example #27
Source File: HibernateUtils.java From at.info-knowledge-base with MIT License | 5 votes |
private static SessionFactory configureSessionFactory(final String dataSource) { final Configuration configuration = new Configuration().configure(dataSource); final ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder() .applySettings(configuration.getProperties()).build(); return configuration.buildSessionFactory(serviceRegistry); }
Example #28
Source File: StartupDataLoader.java From maven-framework-project with MIT License | 5 votes |
/** * Constructing a new Hibernate SessionFactory for every request would cause very poor performance. However, * Java servlets must be thread-safe, so we can't use a SessionFactory as an instance variable. This method provides * thread-safe access to a SessionFactory, so the startup data loader and the search servlet can open Hibernate sessions * more efficiently. * * @return Session */ public static synchronized Session openSession() { if(sessionFactory == null) { Configuration configuration = new Configuration(); configuration.configure(); ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry(); sessionFactory = configuration.buildSessionFactory(serviceRegistry); } return sessionFactory.openSession(); }
Example #29
Source File: HibernateUtil.java From tutorials with MIT License | 5 votes |
private static SessionFactory buildSessionFactory() { try { // Create a session factory from immutable.cfg.xml Configuration configuration = new Configuration(); configuration.addAnnotatedClass(Event.class); configuration.addAnnotatedClass(EventGeneratedId.class); configuration.configure("immutable.cfg.xml"); ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build(); return configuration.buildSessionFactory(serviceRegistry); } catch (Throwable ex) { System.out.println("Initial SessionFactory creation failed." + ex); throw new ExceptionInInitializerError(ex); } }
Example #30
Source File: BatchFetchTest.java From hibernate-reactive with GNU Lesser General Public License v2.1 | 5 votes |
@Override protected Configuration constructConfiguration() { Configuration configuration = super.constructConfiguration(); configuration.addAnnotatedClass( Node.class ); configuration.addAnnotatedClass( Element.class ); return configuration; }