Java Code Examples for org.hibernate.cfg.Configuration

The following examples show how to use org.hibernate.cfg.Configuration. These examples are extracted from open source projects. 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 want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: Transwarp-Sample-Code   Source File: InHibernate.java    License: MIT License 6 votes vote down vote up
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
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 Project: redisson   Source File: ReadWriteTest.java    License: Apache License 2.0 6 votes vote down vote up
@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
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 Project: yeti   Source File: HibernateUtil.java    License: MIT License 6 votes vote down vote up
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
/** {@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
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 Project: olat   Source File: ITCaseDailyStatHsqldbSchema.java    License: Apache License 2.0 6 votes vote down vote up
@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 Project: journaldev   Source File: HibernateUtil.java    License: MIT License 6 votes vote down vote up
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
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
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 Project: serverless   Source File: HibernateUtil.java    License: Apache License 2.0 6 votes vote down vote up
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
@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
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 Project: dkpro-jwpl   Source File: WikiHibernateUtil.java    License: Apache License 2.0 6 votes vote down vote up
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
@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 Project: olat   Source File: OLATLocalSessionFactoryBean.java    License: Apache License 2.0 5 votes vote down vote up
@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
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
@Override
protected Configuration constructConfiguration() {
	Configuration configuration = super.constructConfiguration();
	configuration.addAnnotatedClass( SecondaryTableTest.Book.class );
	configuration.addAnnotatedClass( SecondaryTableTest.Author.class );
	return configuration;
}
 
Example 20
Source Project: hibernate-demos   Source File: AbstractCachingDemo.java    License: Apache License 2.0 5 votes vote down vote up
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
@Override
protected Configuration constructConfiguration() {
	Configuration configuration = super.constructConfiguration();
	configuration.addAnnotatedClass( Book.class );
	configuration.addAnnotatedClass( Author.class );
	return configuration;
}
 
Example 22
Source Project: Quelea   Source File: HibernateUtil.java    License: GNU General Public License v3.0 5 votes vote down vote up
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
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 Project: tutorials   Source File: HibernateExceptionUnitTest.java    License: MIT License 5 votes vote down vote up
@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
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 Project: sailfish-core   Source File: SFLocalContext.java    License: Apache License 2.0 5 votes vote down vote up
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 Project: at.info-knowledge-base   Source File: HibernateUtils.java    License: MIT License 5 votes vote down vote up
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 Project: maven-framework-project   Source File: StartupDataLoader.java    License: MIT License 5 votes vote down vote up
/**
 * 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 Project: tutorials   Source File: HibernateUtil.java    License: MIT License 5 votes vote down vote up
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
@Override
protected Configuration constructConfiguration() {
	Configuration configuration = super.constructConfiguration();
	configuration.addAnnotatedClass( Node.class );
	configuration.addAnnotatedClass( Element.class );
	return configuration;
}
 
Example 31
protected final Configuration buildConfiguration() {

		Configuration cfg = new Configuration().setProperties( buildProperties() );


		String[] mappingFiles = PropertiesHelper.toStringArray( mapResources, " ,\n\t\r\f" );
		for ( int i = 0; i < mappingFiles.length; i++ ) {
			cfg.addResource( mappingFiles[i] );
		}

		if ( customListeners != null && !customListeners.isEmpty() ) {
			Iterator entries = customListeners.entrySet().iterator();
			while ( entries.hasNext() ) {
				final Map.Entry entry = ( Map.Entry ) entries.next();
				final String type = ( String ) entry.getKey();
				final Object value = entry.getValue();
				if ( value != null ) {
					if ( String.class.isAssignableFrom( value.getClass() ) ) {
						// Its the listener class name
						cfg.setListener( type, ( ( String ) value ) );
					}
					else {
						// Its the listener instance (or better be)
						cfg.setListener( type, value );
					}
				}
			}
		}

		return cfg;
	}
 
Example 32
Source Project: glowroot   Source File: HibernateUtil.java    License: Apache License 2.0 5 votes vote down vote up
private static SessionFactory createSessionFactory() throws Exception {
    Configuration configuration;
    try {
        configuration = new Configuration().configure();
    } catch (MappingException e) {
        // hibernate prior to 3.6.0
        Class<?> cfgClass = Class.forName("org.hibernate.cfg.AnnotationConfiguration");
        configuration = ((Configuration) cfgClass.newInstance()).configure();
    }
    return configuration.buildSessionFactory();
}
 
Example 33
Source Project: ignite   Source File: CacheHibernateStoreSessionListener.java    License: Apache License 2.0 5 votes vote down vote up
/** {@inheritDoc} */
@SuppressWarnings("deprecation")
@Override public void start() throws IgniteException {
    if (sesFactory == null && F.isEmpty(hibernateCfgPath)) {
        throw new IgniteException("Either session factory or Hibernate configuration file is required by " +
            getClass().getSimpleName() + '.');
    }

    if (!F.isEmpty(hibernateCfgPath)) {
        if (sesFactory == null) {
            try {
                URL url = new URL(hibernateCfgPath);

                sesFactory = new Configuration().configure(url).buildSessionFactory();
            }
            catch (MalformedURLException ex) {
                log.warning("Exception on store listener start", ex);
            }

            if (sesFactory == null) {
                File cfgFile = new File(hibernateCfgPath);

                if (cfgFile.exists())
                    sesFactory = new Configuration().configure(cfgFile).buildSessionFactory();
            }

            if (sesFactory == null)
                sesFactory = new Configuration().configure(hibernateCfgPath).buildSessionFactory();

            if (sesFactory == null)
                throw new IgniteException("Failed to resolve Hibernate configuration file: " + hibernateCfgPath);

            closeSesOnStop = true;
        }
        else {
            U.warn(log, "Hibernate configuration file configured in " + getClass().getSimpleName() +
                " will be ignored (session factory is already set).");
        }
    }
}
 
Example 34
public static void main(String[] args) {
	
	Configuration configuration = new Configuration().configure().setNamingStrategy(new ImprovedNamingStrategy());
	EnversSchemaGenerator generator = new EnversSchemaGenerator(configuration);
	SchemaExport export = generator.export();
	
	export.setFormat(false);
	export.setOutputFile("src/test/resources/h2schma.sql");
	export.create(true, false);
}
 
Example 35
@Override
protected Configuration constructConfiguration() {
	Configuration configuration = super.constructConfiguration();
	configuration.addAnnotatedClass( Node.class );
	configuration.addAnnotatedClass( Element.class );
	return configuration;
}
 
Example 36
public void configure(Configuration cfg) {
	super.configure( cfg );
	cfg.setProperty( Environment.USE_QUERY_CACHE, "true" );
	cfg.setProperty( Environment.CACHE_REGION_PREFIX, "foo" );
	cfg.setProperty( Environment.USE_SECOND_LEVEL_CACHE, "true" );
	cfg.setProperty( Environment.GENERATE_STATISTICS, "true" );
}
 
Example 37
Source Project: redisson   Source File: CollectionTest.java    License: Apache License 2.0 5 votes vote down vote up
@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.SHOW_SQL, "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());
}
 
Example 38
Source Project: primefaces-blueprints   Source File: HibernateUtil.java    License: The Unlicense 5 votes vote down vote up
private static SessionFactory buildSessionFactory() throws HibernateException {
    Configuration configuration = new Configuration().configure();
    // configures settings from hibernate.cfg.xml

    StandardServiceRegistryBuilder serviceRegistryBuilder = new StandardServiceRegistryBuilder();

    // If you miss the below line then it will complain about a missing dialect setting
    serviceRegistryBuilder.applySettings(configuration.getProperties());

    ServiceRegistry serviceRegistry = serviceRegistryBuilder.build();
    return configuration.buildSessionFactory(serviceRegistry);
}
 
Example 39
Source Project: primefaces-blueprints   Source File: HibernateUtil.java    License: The Unlicense 5 votes vote down vote up
private static SessionFactory buildSessionFactory() throws HibernateException {
    Configuration configuration = new Configuration().configure();
    // configures settings from hibernate.cfg.xml

    StandardServiceRegistryBuilder serviceRegistryBuilder = new StandardServiceRegistryBuilder();

    // If you miss the below line then it will complain about a missing dialect setting
    serviceRegistryBuilder.applySettings(configuration.getProperties());

    ServiceRegistry serviceRegistry = serviceRegistryBuilder.build();
    return configuration.buildSessionFactory(serviceRegistry);
}
 
Example 40
@Override
protected Configuration newConfiguration() throws HibernateException {
	return new Configuration() {
		@Override
		public void addFilterDefinition(FilterDefinition definition) {
			registeredFilterDefinitions.add(definition);
		}
	};
}