Java Code Examples for org.hibernate.cfg.Configuration#buildSessionFactory()

The following examples show how to use org.hibernate.cfg.Configuration#buildSessionFactory() . 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 check out the related API usage on the sidebar.
Example 1
public void testOutOfOrder() {
	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/Person.hbm.xml" );
		cfg.addResource( getBaseForMappings() + "extendshbm/Employee.hbm.xml" );

		cfg.buildSessionFactory();

		assertNotNull( cfg.getClassMapping( "org.hibernate.test.extendshbm.Customer" ) );
		assertNotNull( cfg.getClassMapping( "org.hibernate.test.extendshbm.Person" ) );
		assertNotNull( cfg.getClassMapping( "org.hibernate.test.extendshbm.Employee" ) );

	}
	catch ( HibernateException e ) {
		fail( "should not fail with exception! " + e );
	}

}
 
Example 2
Source Project: 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) {
        // Make sure you log the exception, as it might be swallowed
        System.err.println("Initial SessionFactory creation failed." + ex);
        throw new ExceptionInInitializerError(ex);
    }
}
 
Example 3
public static SessionFactory buildSessionFactory(Class<?> testClass){
    Configuration configuration = new Configuration();
    configuration.setProperty("connection.driver_class","org.h2.Driver");
    configuration.setProperty("hibernate.connection.url", "jdbc:h2:mem:" + testClass.getSimpleName());
    configuration.setProperty("hibernate.connection.username", "sa");
    configuration.setProperty("hibernate.connection.password", "");
    configuration.setProperty("dialect", "org.hibernate.dialect.H2Dialect");
    configuration.setProperty("hibernate.hbm2ddl.auto", "update");
    configuration.setProperty("show_sql", "true");
    configuration.setProperty(" hibernate.connection.pool_size", "10");

    Reflections reflections = new Reflections("io.robe.hibernate.test.entity");

    Set<Class<?>> classes = reflections.getTypesAnnotatedWith(javax.persistence.Entity.class);

    for(Class<?> clazz : classes) {
        configuration.addAnnotatedClass(clazz);
    }

    ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
    return configuration.buildSessionFactory(serviceRegistry);
}
 
Example 4
private SessionFactory newSessionFactory() {
    Properties properties = getProperties();
    Configuration configuration = new Configuration().addProperties(properties);
    for(Class<?> entityClass : entities()) {
        configuration.addAnnotatedClass(entityClass);
    }
    String[] packages = packages();
    if(packages != null) {
        for(String scannedPackage : packages) {
            configuration.addPackage(scannedPackage);
        }
    }
    Interceptor interceptor = interceptor();
    if(interceptor != null) {
        configuration.setInterceptor(interceptor);
    }
    return configuration.buildSessionFactory(
            new StandardServiceRegistryBuilder()
                    .applySettings(properties)
                    .build()
    );
}
 
Example 5
Source Project: journaldev   File: HibernateAnnotationUtil.java    License: MIT License 6 votes vote down vote up
private static SessionFactory buildSessionFactory() {
    try {
        // Create the SessionFactory from hibernate-annotation.cfg.xml
    	Configuration configuration = new Configuration();
    	configuration.configure("hibernate-annotation.cfg.xml");
    	System.out.println("Hibernate Annotation Configuration loaded");
    	
    	ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
    	System.out.println("Hibernate Annotation 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 6
Source Project: Project   File: CRUDTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void stateTest(){
    Configuration configuration = new Configuration();
    configuration.configure();

    SessionFactory sessionFactory = configuration.buildSessionFactory();
    Session session = sessionFactory.openSession();

    Transaction transaction = session.beginTransaction();

    User user = new User();
    // 瞬时态对象:没有持久化标识 OID,没有被 session 管理

    user.setUsername("persistent");
    Serializable id = session.save(user);
    // 这里是持久态对象:有持久化标识 OID,被 session 管理

    transaction.commit();

    session.close();
    sessionFactory.close();
    System.out.println(user);
    // 这里是托管态对象:有持久化标识 OID,没有被 session 管理
}
 
Example 7
public void configureSession(Properties props, List<Class> classes) {
    Configuration cfg = new Configuration();
    cfg.setProperties(props);

    if (classes != null) {
        for (Class className : classes) {
            cfg.addClass(className);
        }
    }

    _factory = cfg.buildSessionFactory();         // get a session context        

    // check tables exist and are of a matching format to the persisted objects
    new SchemaUpdate(cfg).execute(false, true);
}
 
Example 8
/** initialises hibernate and the required tables */
private void initialise(Set<Class> classes, Properties props) throws HibernateException {
    try {
        Configuration _cfg = new Configuration();

        // if props supplied, use them instead of hibernate.properties
        if (props != null) {
            _cfg.setProperties(props);
        }

        // add each persisted class to config
        for (Class persistedClass : classes) {
            _cfg.addClass(persistedClass);
        }

        // get a session context
        ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
                .applySettings(_cfg.getProperties()).build();
        _factory = _cfg.buildSessionFactory(serviceRegistry);

        // check tables exist and are of a matching format to the persisted objects
        new SchemaUpdate(_cfg).execute(false, true);

    }
    catch (MappingException me) {
        _log.error("Could not initialise database connection.", me);
    }
}
 
Example 9
Source Project: hibernate-demos   File: AbstractDemo.java    License: Apache License 2.0 5 votes vote down vote up
protected AbstractDemo(Class<?>... entities) {
	final Configuration configuration = new Configuration();
	for (Class<?> entity : entities) {
		configuration.addAnnotatedClass( entity );
	}
	sessionFactory = configuration.buildSessionFactory(
			new StandardServiceRegistryBuilder().build() );
}
 
Example 10
Source Project: HibernateDemos   File: AbstractCachingDemo.java    License: The Unlicense 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 11
private  SessionFactory configureSessionFactory()
		throws HibernateException {
	Configuration configuration = new Configuration();
	configuration.configure();
	StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder()
			.applySettings(configuration.getProperties());
	SessionFactory sessionfactory = configuration
			.buildSessionFactory(builder.build());
	return sessionfactory;
}
 
Example 12
/**
 * 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 13
private synchronized static void initInSightsDAL(){
	if(sessionFactory == null){
		Configuration configuration = new Configuration().configure();
		configuration.addAnnotatedClass(UserPortfolio.class);
		configuration.addAnnotatedClass(CustomDashboard.class);
		configuration.addAnnotatedClass(ProjectMapping.class);
		configuration.addAnnotatedClass(AgentConfig.class);
		configuration.addAnnotatedClass(ToolsLayout.class);
		configuration.addAnnotatedClass(EntityDefinition.class);
		configuration.addAnnotatedClass(HierarchyDetails.class);
		configuration.addAnnotatedClass(HierarchyMapping.class);
		configuration.addAnnotatedClass(Icon.class);
		configuration.addAnnotatedClass(SettingsConfiguration.class);
		configuration.addAnnotatedClass(QueryBuilderConfig.class);
		configuration.addAnnotatedClass(WebHookConfig.class);
		configuration.addAnnotatedClass(CorrelationConfiguration.class);
		configuration.addAnnotatedClass(RelationshipConfiguration.class);
		configuration.addAnnotatedClass(WebhookDerivedConfig.class);
		PostgreData postgre = ApplicationConfigProvider.getInstance().getPostgre();
		if(postgre != null){
			configuration.setProperty("hibernate.connection.username", postgre.getUserName());
			configuration.setProperty("hibernate.connection.password", postgre.getPassword());
			configuration.setProperty("hibernate.connection.url", postgre.getInsightsDBUrl());
		}
		StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties());
		sessionFactory = configuration.buildSessionFactory(builder.build());
	}
}
 
Example 14
/**
 * @param igniteInstanceName Name of the grid providing caches.
 * @return Session factory.
 */
private SessionFactory startHibernate(String igniteInstanceName) {
    Configuration cfg = hibernateConfiguration(igniteInstanceName);

    StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder();

    builder.applySetting("hibernate.connection.url", CONNECTION_URL);
    builder.applySetting("hibernate.show_sql", false);
    builder.applySettings(cfg.getProperties());

    return cfg.buildSessionFactory(builder.build());
}
 
Example 15
Source Project: r-course   File: HibernateFabric.java    License: MIT License 5 votes vote down vote up
/**
 * Configuration of session factory with Fabric integration.
 */
public static SessionFactory createSessionFactory(String fabricUrl, String username, String password, String fabricUser, String fabricPassword)
        throws Exception {
    // creating this here allows passing needed params to the constructor
    FabricMultiTenantConnectionProvider connProvider = new FabricMultiTenantConnectionProvider(fabricUrl, "employees", "employees", username, password,
            fabricUser, fabricPassword);
    ServiceRegistryBuilder srb = new ServiceRegistryBuilder();
    srb.addService(org.hibernate.service.jdbc.connections.spi.MultiTenantConnectionProvider.class, connProvider);
    srb.applySetting("hibernate.dialect", "org.hibernate.dialect.MySQLInnoDBDialect");

    Configuration config = new Configuration();
    config.setProperty("hibernate.multiTenancy", "DATABASE");
    config.addResource("com/mysql/fabric/demo/employee.hbm.xml");
    return config.buildSessionFactory(srb.buildServiceRegistry());
}
 
Example 16
Source Project: primefaces-blueprints   File: AccountsDAO.java    License: The Unlicense 5 votes vote down vote up
private  SessionFactory configureSessionFactory()
		throws HibernateException {
	Configuration configuration = new Configuration();
	configuration.configure();
	StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder()
			.applySettings(configuration.getProperties());
	SessionFactory sessionfactory = configuration
			.buildSessionFactory(builder.build());
	return sessionfactory;
}
 
Example 17
Source Project: kardio   File: HibernateConfig.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * Constructor to initialize the hibernate configuration
 */
private HibernateConfig(){
	logger.info("** Initializing Hibernate Connection **");
	Configuration configuration = new Configuration();

	configuration.addAnnotatedClass(com.tmobile.kardio.surveiller.db.entity.AlertSubscriptionEntity.class);
	configuration.addAnnotatedClass(com.tmobile.kardio.surveiller.db.entity.ComponentEntity.class);
	configuration.addAnnotatedClass(com.tmobile.kardio.surveiller.db.entity.ComponentFailureLogEntity.class);
	configuration.addAnnotatedClass(com.tmobile.kardio.surveiller.db.entity.ComponentTypeEntity.class);
	configuration.addAnnotatedClass(com.tmobile.kardio.surveiller.db.entity.CounterEntity.class);
	configuration.addAnnotatedClass(com.tmobile.kardio.surveiller.db.entity.CounterMetricEntity.class);
	configuration.addAnnotatedClass(com.tmobile.kardio.surveiller.db.entity.CounterMetricHistoryEntity.class);
	configuration.addAnnotatedClass(com.tmobile.kardio.surveiller.db.entity.CounterMetricTypeEntity.class);
	configuration.addAnnotatedClass(com.tmobile.kardio.surveiller.db.entity.DaillyCompStatusEntity.class);
	configuration.addAnnotatedClass(com.tmobile.kardio.surveiller.db.entity.EnvCounterEntity.class);
	configuration.addAnnotatedClass(com.tmobile.kardio.surveiller.db.entity.EnvironmentEntity.class);
	configuration.addAnnotatedClass(com.tmobile.kardio.surveiller.db.entity.HealthCheckEntity.class);
	configuration.addAnnotatedClass(com.tmobile.kardio.surveiller.db.entity.HealthCheckParamEntity.class);
	configuration.addAnnotatedClass(com.tmobile.kardio.surveiller.db.entity.HealthCheckTypeEntity.class);
	configuration.addAnnotatedClass(com.tmobile.kardio.surveiller.db.entity.RegionEntity.class);
	configuration.addAnnotatedClass(com.tmobile.kardio.surveiller.db.entity.StatusEntity.class);
	configuration.addAnnotatedClass(com.tmobile.kardio.surveiller.db.entity.ContainerStatsEntity.class);
	configuration.addAnnotatedClass(com.tmobile.kardio.surveiller.db.entity.ApiStatusEntity.class);
	configuration.addAnnotatedClass(com.tmobile.kardio.surveiller.db.entity.PromLookupEntity.class);
	configuration.addAnnotatedClass(com.tmobile.kardio.surveiller.db.entity.TpsServiceEntity.class);
	configuration.addAnnotatedClass(com.tmobile.kardio.surveiller.db.entity.TpsLatHistoryEntity.class);
	configuration.addAnnotatedClass(com.tmobile.kardio.surveiller.db.entity.K8sApiStatusEntity.class);
	configuration.addAnnotatedClass(com.tmobile.kardio.surveiller.db.entity.K8sTpsLatHistoryEntity.class);
	configuration.addAnnotatedClass(com.tmobile.kardio.surveiller.db.entity.K8sObjectPodsEntity.class);
	configuration.addAnnotatedClass(com.tmobile.kardio.surveiller.db.entity.K8sPodsContainersEntity.class);
	
	configuration.setProperty("hibernate.connection.driver_class", propertyUtil.getValue(SurveillerConstants.CONFIG_DB_DRIVER_CLASS) );
    configuration.setProperty("hibernate.connection.url", propertyUtil.getValue(SurveillerConstants.CONFIG_DB_URL) );                                
    configuration.setProperty("hibernate.connection.username", propertyUtil.getValue(SurveillerConstants.CONFIG_DB_USERNAME) );     
    configuration.setProperty("hibernate.connection.password", propertyUtil.getValue(SurveillerConstants.CONFIG_DB_PASSWORD) );
    configuration.setProperty("hibernate.dialect", propertyUtil.getValue(SurveillerConstants.CONFIG_DB_HIBERNATE_DIALECT) );
    configuration.setProperty("hibernate.hbm2ddl.auto", propertyUtil.getValue(SurveillerConstants.CONFIG_DB_HIBERNATE_HBM2DDL) );
    configuration.setProperty("hibernate.show_sql", propertyUtil.getValue(SurveillerConstants.CONFIG_DB_HIBERNATE_SHOWSQL) );
    configuration.setProperty("hibernate.connection.pool_size", propertyUtil.getValue(SurveillerConstants.CONFIG_DB_HIBERNATE_POOLSIZE) );
    configuration.setProperty("hibernate.enhancer.enableLazyInitialization", propertyUtil.getValue(SurveillerConstants.CONFIG_DB_HIBERNATE_LX_INIT) );
    configuration.setProperty("hibernate.current_session_context_class", "org.hibernate.context.internal.ThreadLocalSessionContext");
    
    StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties());
	sessionFactory = configuration.buildSessionFactory(builder.build());
	logger.info("** Initializing Hibernate Connection Completed **");
}
 
Example 18
Source Project: hibernate-types   File: AbstractTest.java    License: Apache License 2.0 4 votes vote down vote up
private SessionFactory newLegacySessionFactory() {
    Properties properties = properties();
    Configuration configuration = new Configuration().addProperties(properties);
    for (Class<?> entityClass : entities()) {
        configuration.addAnnotatedClass(entityClass);
    }
    String[] packages = packages();
    if (packages != null) {
        for (String scannedPackage : packages) {
            configuration.addPackage(scannedPackage);
        }
    }
    String[] resources = resources();
    if (resources != null) {
        for (String resource : resources) {
            configuration.addResource(resource);
        }
    }
    Interceptor interceptor = interceptor();
    if (interceptor != null) {
        configuration.setInterceptor(interceptor);
    }

    final List<Type> additionalTypes = additionalTypes();
    if (additionalTypes != null) {
        configuration.registerTypeContributor((typeContributions, serviceRegistry) -> {
            additionalTypes.stream().forEach(type -> {
                if (type instanceof BasicType) {
                    typeContributions.contributeType((BasicType) type);
                } else if (type instanceof UserType) {
                    typeContributions.contributeType((UserType) type);
                } else if (type instanceof CompositeUserType) {
                    typeContributions.contributeType((CompositeUserType) type);
                }
            });
        });
    }
    return configuration.buildSessionFactory(
            new StandardServiceRegistryBuilder()
                    .applySettings(properties)
                    .build()
    );
}
 
Example 19
Source Project: coditori   File: Utils.java    License: Apache License 2.0 4 votes vote down vote up
public static SessionFactory getSessionFactory() {
        Configuration configuration = new Configuration();
//        configuration.addResource("customer.hbm.xml");
        configuration.addAnnotatedClass(com.massoudafrashteh.code.hibernate.model.User.class);
        return configuration.buildSessionFactory();
    }
 
Example 20
private static void initSessionFactory() {
	logger.info("Initializing hibernate Session Factory Described by [" + DAOConfig.getHibernateConfigurationFile() + "]");

	Configuration conf = setDialectPropertyToConfiguration();

	sessionFactory = conf.buildSessionFactory();

}