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 Project: Transwarp-Sample-Code   Author: TranswarpCN   File: InHibernate.java    License: MIT License 8 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
Source Project: cacheonix-core   Author: cacheonix   File: ExtendsTest.java    License: GNU Lesser General Public License v2.1 6 votes vote down vote up
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   Author: redisson   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
Source Project: Knowage-Server   Author: KnowageLabs   File: HibernateDataSource.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
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   Author: sensepost   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
Source Project: ignite   Author: apache   File: CacheHibernateStoreSessionListenerSelfTest.java    License: Apache License 2.0 6 votes vote down vote up
/** {@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 Project: cacheonix-core   Author: cacheonix   File: ExtendsTest.java    License: GNU Lesser General Public License v2.1 6 votes vote down vote up
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   Author: huihoo   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   Author: journaldev   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
Source Project: google-cloud-spanner-hibernate   Author: GoogleCloudPlatform   File: BaseCoreFunctionalTestCase.java    License: GNU Lesser General Public License v2.1 6 votes vote down vote up
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 Project: google-cloud-spanner-hibernate   Author: GoogleCloudPlatform   File: BaseCoreFunctionalTestCase.java    License: GNU Lesser General Public License v2.1 6 votes vote down vote up
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   Author: arun-gupta   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
Source Project: spring4-understanding   Author: langtianya   File: LocalSessionFactoryBeanTests.java    License: Apache License 2.0 6 votes vote down vote up
@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 Project: cacheonix-core   Author: cacheonix   File: MigrationTest.java    License: GNU Lesser General Public License v2.1 6 votes vote down vote up
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   Author: dkpro   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
Source Project: spring4-understanding   Author: langtianya   File: LocalSessionFactoryBeanTests.java    License: Apache License 2.0 5 votes vote down vote up
@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   Author: huihoo   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
Source Project: cacheonix-core   Author: cacheonix   File: AggressiveReleaseTest.java    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
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 Project: hibernate-reactive   Author: hibernate   File: SecondaryTableTest.java    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
@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   Author: hibernate   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
Source Project: hibernate-reactive   Author: hibernate   File: LazyPropertyTest.java    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
protected Configuration constructConfiguration() {
	Configuration configuration = super.constructConfiguration();
	configuration.addAnnotatedClass( Book.class );
	configuration.addAnnotatedClass( Author.class );
	return configuration;
}
 
Example #22
Source Project: Quelea   Author: quelea-projection   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
Source Project: scheduling   Author: ow2-proactive   File: SchedulerDBManager.java    License: GNU Affero General Public License v3.0 5 votes vote down vote up
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   Author: eugenp   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
Source Project: cacheonix-core   Author: cacheonix   File: CMTTest.java    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
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   Author: exactpro   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   Author: atinfo   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   Author: v5developer   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   Author: eugenp   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
Source Project: hibernate-reactive   Author: hibernate   File: BatchFetchTest.java    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
protected Configuration constructConfiguration() {
	Configuration configuration = super.constructConfiguration();
	configuration.addAnnotatedClass( Node.class );
	configuration.addAnnotatedClass( Element.class );
	return configuration;
}