Java Code Examples for org.hibernate.boot.registry.StandardServiceRegistryBuilder

The following examples show how to use org.hibernate.boot.registry.StandardServiceRegistryBuilder. 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
Source Project: tutorials   Source File: HibernateWhereJoinTableIntegrationTest.java    License: MIT License 6 votes vote down vote up
@BeforeClass
public static void beforeTests() {
    Configuration configuration = new Configuration().addAnnotatedClass(User.class)
        .addAnnotatedClass(Group.class)
        .addAnnotatedClass(UserGroupRelation.class)
        .setProperty("hibernate.dialect", H2Dialect.class.getName())
        .setProperty("hibernate.connection.driver_class", org.h2.Driver.class.getName())
        .setProperty("hibernate.connection.url", "jdbc:h2:mem:test")
        .setProperty("hibernate.connection.username", "sa")
        .setProperty("hibernate.connection.password", "")
        .setProperty("hibernate.hbm2ddl.auto", "update");
    
    ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
        .applySettings(configuration.getProperties())
        .build();
    
    sessionFactory = configuration.buildSessionFactory(serviceRegistry);
}
 
Example 2
Source Project: robe   Source File: HibernateUtil.java    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
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 3
@Override
public void contribute(StandardServiceRegistryBuilder serviceRegistryBuilder) {
  serviceRegistryBuilder
      // The custom Hibernate schema management tool for Spanner.
      .addInitiator(new StandardServiceInitiator() {
        @Override
        public Service initiateService(Map configurationValues,
            ServiceRegistryImplementor registry) {
          return SCHEMA_MANAGEMENT_TOOL;
        }

        @Override
        public Class getServiceInitiated() {
          return SchemaManagementTool.class;
        }
      })
      // The user agent JDBC connection property to identify the library.
      .applySetting("hibernate.connection.userAgent", HIBERNATE_API_CLIENT_LIB_TOKEN)
      // Create a unique index for a table if it does not already exist when in UPDATE mode.
      .applySetting(
          "hibernate.schema_update.unique_constraint_strategy",
          UniqueConstraintSchemaUpdateStrategy.RECREATE_QUIETLY)
      // Allows entities to be used with InheritanceType.JOINED in Spanner.
      .applySetting("hibernate.hql.bulk_id_strategy", InlineIdsOrClauseBulkIdStrategy.INSTANCE);
}
 
Example 4
/**
 * Set up the metadata for Hibernate to generate schema statements.
 */
@Before
public void setup() throws SQLException {
  JDBCMockObjectFactory jdbcMockObjectFactory = new JDBCMockObjectFactory();
  jdbcMockObjectFactory.registerMockDriver();

  this.connection = jdbcMockObjectFactory.getMockConnection();
  this.connection.setMetaData(MockJdbcUtils.metaDataBuilder().build());
  jdbcMockObjectFactory.getMockDriver().setupConnection(this.connection);

  this.registry = new StandardServiceRegistryBuilder()
      .applySetting("hibernate.dialect", SpannerDialect.class.getName())
      .applySetting("hibernate.connection.url", "unused")
      .build();

  this.metadata =
      new MetadataSources(this.registry).addAnnotatedClass(TestEntity.class).buildMetadata();
}
 
Example 5
Source Project: journaldev   Source File: HibernateUtil.java    License: MIT License 6 votes vote down vote up
private static SessionFactory buildSessionAnnotationFactory() {
   	try {
           // Create the SessionFactory from hibernate.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) {
           // Make sure you log the exception, as it might be swallowed
           System.err.println("Initial SessionFactory creation failed." + ex);
           throw new ExceptionInInitializerError(ex);
       }
}
 
Example 6
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 7
Source Project: tutorials   Source File: PersistJSONUnitTest.java    License: MIT License 6 votes vote down vote up
@Before
public void init() {
    try {
        Configuration configuration = new Configuration();

        Properties properties = new Properties();
        properties.load(Thread.currentThread()
            .getContextClassLoader()
            .getResourceAsStream("hibernate-persistjson.properties"));

        configuration.setProperties(properties);

        ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties())
            .build();
        MetadataSources metadataSources = new MetadataSources(serviceRegistry);
        metadataSources.addAnnotatedClass(Customer.class);

        SessionFactory factory = metadataSources.buildMetadata()
            .buildSessionFactory();

        session = factory.openSession();
    } catch (HibernateException | IOException e) {
        fail("Failed to initiate Hibernate Session [Exception:" + e.toString() + "]");
    }
}
 
Example 8
public HibernateDatabase(Properties properties) throws HibernateException {

        StandardServiceRegistry registry = new StandardServiceRegistryBuilder().applySettings(properties).build();
        MetadataSources metadataSources = new MetadataSources(registry);
        metadataSources.addAnnotatedClass(SystemInfo.class)
            .addAnnotatedClass(Project.class)
            .addAnnotatedClass(Runner.class)
            .addAnnotatedClass(Repository.class)
            .addAnnotatedClass(RepositoryType.class)
            .addAnnotatedClass(SystemUnderTest.class)
            .addAnnotatedClass(Requirement.class)
            .addAnnotatedClass(Specification.class)
            .addAnnotatedClass(Reference.class)
            .addAnnotatedClass(Execution.class);

        this.properties = properties;
        this.metadata = metadataSources.buildMetadata();

    }
 
Example 9
Source Project: tutorials   Source File: HibernateUtil.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.addAnnotatedClass(Employee.class);
        configuration.addAnnotatedClass(Project.class);
        configuration.configure("manytomany.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 10
Source Project: tutorials   Source File: HibernateLoggingIntegrationTest.java    License: MIT License 6 votes vote down vote up
@Before
public void setUp() throws IOException {
    final StandardServiceRegistry registry = new StandardServiceRegistryBuilder().configure("hibernate-logging.cfg.xml")
        .build();
    try {
        sessionFactory = new MetadataSources(registry).buildMetadata()
            .buildSessionFactory();
        Session session = sessionFactory.openSession();
        session.beginTransaction();
        session.save(new Employee("John Smith", "001"));
        session.getTransaction()
            .commit();
        session.close();
    } catch (Exception e) {
        fail(e);
        StandardServiceRegistryBuilder.destroy(registry);
    }
}
 
Example 11
Source Project: lambda-rds-mysql   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 12
Source Project: teiid-spring-boot   Source File: TeiidServer.java    License: Apache License 2.0 6 votes vote down vote up
private Metadata getMetadata(Set<BeanDefinition> components, PhysicalNamingStrategy namingStrategy,
        MetadataFactory mf) {
    ServiceRegistry registry = metadataSources.getServiceRegistry();
    StandardServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder(
            (BootstrapServiceRegistry) registry).applySetting(AvailableSettings.DIALECT, TeiidDialect.class)
            .build();
    // Generate Hibernate model based on @Entity definitions
    for (BeanDefinition c : components) {
        try {
            Class<?> clazz = Class.forName(c.getBeanClassName());
            metadataSources.addAnnotatedClass(clazz);
        } catch (ClassNotFoundException e) {
        }
    }
    return metadataSources.getMetadataBuilder(serviceRegistry).applyPhysicalNamingStrategy(namingStrategy).build();
}
 
Example 13
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 14
Source Project: collect-earth   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");
    	
    	configuration.addAnnotatedClass(Plot.class); 
    	
    	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 15
Source Project: lams   Source File: SchemaUpdate.java    License: GNU General Public License v2.0 6 votes vote down vote up
private static StandardServiceRegistry buildStandardServiceRegistry(CommandLineArgs parsedArgs) throws Exception {
	final BootstrapServiceRegistry bsr = new BootstrapServiceRegistryBuilder().build();
	final StandardServiceRegistryBuilder ssrBuilder = new StandardServiceRegistryBuilder( bsr );

	if ( parsedArgs.cfgXmlFile != null ) {
		ssrBuilder.configure( parsedArgs.cfgXmlFile );
	}

	if ( parsedArgs.propertiesFile != null ) {
		Properties props = new Properties();
		props.load( new FileInputStream( parsedArgs.propertiesFile ) );
		ssrBuilder.applySettings( props );
	}

	return ssrBuilder.build();
}
 
Example 16
Source Project: tutorials   Source File: BootstrapAPIIntegrationTest.java    License: MIT License 6 votes vote down vote up
@Test
public void whenServiceRegistryAndMetadata_thenSessionFactory() throws IOException {

    BootstrapServiceRegistry bootstrapRegistry = new BootstrapServiceRegistryBuilder()
            .build();

    ServiceRegistry standardRegistry = new StandardServiceRegistryBuilder(bootstrapRegistry)
            // No need for hibernate.cfg.xml file, an hibernate.properties is sufficient.
            //.configure()
            .build();

    MetadataSources metadataSources = new MetadataSources(standardRegistry);
    metadataSources.addAnnotatedClass(Movie.class);

    Metadata metadata = metadataSources.getMetadataBuilder().build();

    sessionFactory = metadata.buildSessionFactory();
    assertNotNull(sessionFactory);
    sessionFactory.close();
}
 
Example 17
@SuppressWarnings("unchecked")
private void processConfigXml(
		LoadedConfig loadedConfig,
		MergedSettings mergedSettings,
		StandardServiceRegistryBuilder ssrBuilder) {
	if ( ! mergedSettings.configurationValues.containsKey( SESSION_FACTORY_NAME ) ) {
		// there is not already a SF-name in the merged settings
		final String sfName = loadedConfig.getSessionFactoryName();
		if ( sfName != null ) {
			// but the cfg.xml file we are processing named one..
			mergedSettings.configurationValues.put( SESSION_FACTORY_NAME, sfName );
		}
	}

	mergedSettings.configurationValues.putAll( loadedConfig.getConfigurationValues() );
	ssrBuilder.configure( loadedConfig );
}
 
Example 18
private void configure(StandardServiceRegistryBuilder ssrBuilder) {

		applyJdbcConnectionProperties( ssrBuilder );
		applyTransactionProperties( ssrBuilder );

		// flush before completion validation
		if ( "true".equals( configurationValues.get( Environment.FLUSH_BEFORE_COMPLETION ) ) ) {
			ssrBuilder.applySetting( Environment.FLUSH_BEFORE_COMPLETION, "false" );
			LOG.definingFlushBeforeCompletionIgnoredInHem( Environment.FLUSH_BEFORE_COMPLETION );
		}

//		final StrategySelector strategySelector = ssrBuilder.getBootstrapServiceRegistry().getService( StrategySelector.class );
//		final Object interceptorSetting = configurationValues.remove( AvailableSettings.SESSION_INTERCEPTOR );
//		if ( interceptorSetting != null ) {
//			settings.setSessionInterceptorClass(
//					loadSessionInterceptorClass( interceptorSetting, strategySelector )
//			);
//		}
	}
 
Example 19
Source Project: hibernate-demos   Source File: BasicOrmDemo.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Open session.
 *
 * @return the session
 */
private static Session openSession() {
	if (sessionFactory == null) {
		final Configuration configuration = new Configuration();
		configuration.addAnnotatedClass( User.class );
		configuration.addAnnotatedClass( Tool.class );
		configuration.addAnnotatedClass( Skill.class );
		configuration.addAnnotatedClass( Community.class );
		configuration.addAnnotatedClass( Donation.class );
		configuration.addAnnotatedClass( Comment.class );
		configuration.addAnnotatedClass( ServiceEvent.class );
		configuration.addAnnotatedClass( Project.class );
		
		sessionFactory = configuration.buildSessionFactory( new StandardServiceRegistryBuilder().build() );
	}
	return sessionFactory.openSession();
}
 
Example 20
Source Project: tutorials   Source File: HibernateUtil.java    License: MIT License 6 votes vote down vote up
public static SessionFactory getSessionFactory() {
    try {
        Properties properties = getProperties();
        Configuration configuration = new Configuration();
        configuration.setProperties(properties);
        configuration.addAnnotatedClass(Person.class);
        configuration.addAnnotatedClass(Address.class);
        ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
                .applySettings(configuration.getProperties()).build();
        sessionFactory = configuration.buildSessionFactory(serviceRegistry);
        return sessionFactory;
    } catch (IOException e) {
        e.printStackTrace();
    }
    return sessionFactory;
}
 
Example 21
Source Project: tutorials   Source File: SaveMethodsIntegrationTest.java    License: MIT License 5 votes vote down vote up
@BeforeClass
public static void beforeTests() {
    Configuration configuration = new Configuration().addAnnotatedClass(Person.class).setProperty("hibernate.dialect", HSQLDialect.class.getName()).setProperty("hibernate.connection.driver_class", org.hsqldb.jdbcDriver.class.getName())
            .setProperty("hibernate.connection.url", "jdbc:hsqldb:mem:test").setProperty("hibernate.connection.username", "sa").setProperty("hibernate.connection.password", "").setProperty("hibernate.hbm2ddl.auto", "update");
    ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
    sessionFactory = configuration.buildSessionFactory(serviceRegistry);
}
 
Example 22
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 23
Source Project: wallride   Source File: Hbm2ddl.java    License: Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
	String locationPattern = "classpath:/org/wallride/domain/*";

	final BootstrapServiceRegistry registry = new BootstrapServiceRegistryBuilder().build();
	final MetadataSources metadataSources = new MetadataSources(registry);
	final StandardServiceRegistryBuilder registryBuilder = new StandardServiceRegistryBuilder(registry);

	registryBuilder.applySetting(AvailableSettings.DIALECT, ExtendedMySQL5InnoDBDialect.class.getCanonicalName());
	registryBuilder.applySetting(AvailableSettings.GLOBALLY_QUOTED_IDENTIFIERS, true);
	registryBuilder.applySetting(AvailableSettings.PHYSICAL_NAMING_STRATEGY, PhysicalNamingStrategySnakeCaseImpl.class);

	final PathMatchingResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();
	final Resource[] resources = resourcePatternResolver.getResources(locationPattern);
	final SimpleMetadataReaderFactory metadataReaderFactory = new SimpleMetadataReaderFactory();
	for (Resource resource : resources) {
		MetadataReader metadataReader = metadataReaderFactory.getMetadataReader(resource);
		AnnotationMetadata metadata = metadataReader.getAnnotationMetadata();
		if (metadata.hasAnnotation(Entity.class.getName())) {
			metadataSources.addAnnotatedClass(Class.forName(metadata.getClassName()));
		}
	}

	final StandardServiceRegistryImpl registryImpl = (StandardServiceRegistryImpl) registryBuilder.build();
	final MetadataBuilder metadataBuilder = metadataSources.getMetadataBuilder(registryImpl);

	new SchemaExport()
			.setHaltOnError(true)
			.setDelimiter(";")
			.create(EnumSet.of(TargetType.STDOUT), metadataBuilder.build());
}
 
Example 24
Source Project: primefaces-blueprints   Source File: ServiceCenterDAO.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 25
Source Project: ignite   Source File: HibernateL2CacheSelfTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Starts Hibernate.
 *
 * @param accessType Cache access type.
 * @param igniteInstanceName Ignite instance name.
 * @return Session factory.
 */
private SessionFactory startHibernate(org.hibernate.cache.spi.access.AccessType accessType, String igniteInstanceName) {
    StandardServiceRegistryBuilder builder = registryBuilder();

    for (Map.Entry<String, String> e : hibernateProperties(igniteInstanceName, accessType.name()).entrySet())
        builder.applySetting(e.getKey(), e.getValue());

    // Use the same cache for Entity and Entity2.
    builder.applySetting(REGION_CACHE_PROPERTY + ENTITY2_NAME, ENTITY_NAME);

    StandardServiceRegistry srvcRegistry = builder.build();

    MetadataSources metadataSources = new MetadataSources(srvcRegistry);

    for (Class entityClass : getAnnotatedClasses())
        metadataSources.addAnnotatedClass(entityClass);

    Metadata metadata = metadataSources.buildMetadata();

    for (PersistentClass entityBinding : metadata.getEntityBindings()) {
        if (!entityBinding.isInherited())
            ((RootClass)entityBinding).setCacheConcurrencyStrategy(accessType.getExternalName());
    }

    for (org.hibernate.mapping.Collection collectionBinding : metadata.getCollectionBindings())
        collectionBinding.setCacheConcurrencyStrategy(accessType.getExternalName() );

    return metadata.buildSessionFactory();
}
 
Example 26
Source Project: ignite   Source File: HibernateL2CacheStrategySelfTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * @param accessType Cache access typr.
 * @param igniteInstanceName Name of the grid providing caches.
 * @return Session factory.
 */
private SessionFactory startHibernate(AccessType accessType, String igniteInstanceName) {
    StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder();

    builder.applySetting("hibernate.connection.url", CONNECTION_URL);

    for (Map.Entry<String, String> e : HibernateL2CacheSelfTest.hibernateProperties(igniteInstanceName, accessType.name()).entrySet())
        builder.applySetting(e.getKey(), e.getValue());

    builder.applySetting(USE_STRUCTURED_CACHE, "true");
    builder.applySetting(REGION_CACHE_PROPERTY + ENTITY1_NAME, "cache1");
    builder.applySetting(REGION_CACHE_PROPERTY + ENTITY2_NAME, "cache2");
    builder.applySetting(REGION_CACHE_PROPERTY + DEFAULT_UPDATE_TIMESTAMPS_REGION_UNQUALIFIED_NAME, DEFAULT_UPDATE_TIMESTAMPS_REGION_UNQUALIFIED_NAME);
    builder.applySetting(REGION_CACHE_PROPERTY + DEFAULT_QUERY_RESULTS_REGION_UNQUALIFIED_NAME, DEFAULT_QUERY_RESULTS_REGION_UNQUALIFIED_NAME);

    MetadataSources metadataSources = new MetadataSources(builder.build());

    metadataSources.addAnnotatedClass(Entity1.class);
    metadataSources.addAnnotatedClass(Entity2.class);
    metadataSources.addAnnotatedClass(Entity3.class);
    metadataSources.addAnnotatedClass(Entity4.class);

    Metadata metadata = metadataSources.buildMetadata();

    for (PersistentClass entityBinding : metadata.getEntityBindings()) {
        if (!entityBinding.isInherited())
            ((RootClass)entityBinding).setCacheConcurrencyStrategy(accessType.getExternalName());
    }

    return metadata.buildSessionFactory();
}
 
Example 27
private static void initGrafanaDAL() {
	if(grafanaSessionFactory == null){
		Configuration configuration = new Configuration().configure();
		configuration.addAnnotatedClass(User.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.getGrafanaDBUrl());
			configuration.setProperty("hbm2ddl.auto", "validate");
		}
		StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties());
		grafanaSessionFactory = configuration.buildSessionFactory(builder.build());
	}
}
 
Example 28
Source Project: primefaces-blueprints   Source File: DealerDAO.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 29
Source Project: primefaces-blueprints   Source File: LoginDAO.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 30
Source Project: MirServer-Netty   Source File: DB.java    License: GNU General Public License v3.0 5 votes vote down vote up
public static void init() throws Exception {
	Configuration configuration = new Configuration();
	configuration.configure();

	serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
	ourSessionFactory = configuration.buildSessionFactory();
}