Java Code Examples for org.hibernate.service.ServiceRegistry

The following are top voted examples for showing how to use org.hibernate.service.ServiceRegistry. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: lambda-rds-mysql   File: HibernateUtil.java   Source Code and License 8 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 2
Project: lams   File: Configuration.java   Source Code and License 6 votes vote down vote up
/**
 * Create a {@link SessionFactory} using the properties and mappings in this configuration. The
 * {@link SessionFactory} will be immutable, so changes made to {@code this} {@link Configuration} after
 * building the {@link SessionFactory} will not affect it.
 *
 * @param serviceRegistry The registry of services to be used in creating this session factory.
 *
 * @return The built {@link SessionFactory}
 *
 * @throws HibernateException usually indicates an invalid configuration or invalid mapping information
 */
public SessionFactory buildSessionFactory(ServiceRegistry serviceRegistry) throws HibernateException {
	LOG.debugf( "Preparing to build session factory with filters : %s", filterDefinitions );
	
	buildTypeRegistrations( serviceRegistry );
	secondPassCompile();
	if ( !metadataSourceQueue.isEmpty() ) {
		LOG.incompleteMappingMetadataCacheProcessing();
	}

	validate();

	Environment.verifyProperties( properties );
	Properties copy = new Properties();
	copy.putAll( properties );
	ConfigurationHelper.resolvePlaceHolders( copy );
	Settings settings = buildSettings( copy, serviceRegistry );

	return new SessionFactoryImpl(
			this,
			mapping,
			serviceRegistry,
			settings,
			sessionFactoryObserver
		);
}
 
Example 3
Project: lams   File: MetadataSources.java   Source Code and License 6 votes vote down vote up
public MetadataSources(ServiceRegistry serviceRegistry, EntityResolver entityResolver, NamingStrategy namingStrategy) {
	this.serviceRegistry = serviceRegistry;
	this.entityResolver = entityResolver;
	this.namingStrategy = namingStrategy;

	this.jaxbHelper = new JaxbHelper( this );
	this.metadataBuilder = new MetadataBuilderImpl( this );
	
	// service registry really should be either BootstrapServiceRegistry or StandardServiceRegistry type...
	if ( ! isExpectedServiceRegistryType( serviceRegistry ) ) {
		LOG.debugf(
				"Unexpected ServiceRegistry type [%s] encountered during building of MetadataSources; may cause " +
						"problems later attempting to construct MetadataBuilder",
				serviceRegistry.getClass().getName()
		);
	}
}
 
Example 4
Project: lams   File: MetadataBuilderImpl.java   Source Code and License 6 votes vote down vote up
private static StandardServiceRegistry getStandardServiceRegistry(ServiceRegistry serviceRegistry) {
	if ( serviceRegistry == null ) {
		throw new HibernateException( "ServiceRegistry passed to MetadataBuilder cannot be null" );
	}

	if ( StandardServiceRegistry.class.isInstance( serviceRegistry ) ) {
		return ( StandardServiceRegistry ) serviceRegistry;
	}
	else if ( BootstrapServiceRegistry.class.isInstance( serviceRegistry ) ) {
		log.debugf(
				"ServiceRegistry passed to MetadataBuilder was a BootstrapServiceRegistry; this likely wont end well" +
						"if attempt is made to build SessionFactory"
		);
		return new StandardServiceRegistryBuilder( (BootstrapServiceRegistry) serviceRegistry ).build();
	}
	else {
		throw new HibernateException(
				String.format(
						"Unexpected type of ServiceRegistry [%s] encountered in attempt to build MetadataBuilder",
						serviceRegistry.getClass().getName()
				)
		);
	}
}
 
Example 5
Project: lams   File: SchemaExport.java   Source Code and License 6 votes vote down vote up
public SchemaExport(ServiceRegistry serviceRegistry, Configuration configuration) {
	this.connectionHelper = new SuppliedConnectionProviderConnectionHelper(
			serviceRegistry.getService( ConnectionProvider.class )
	);
	this.sqlStatementLogger = serviceRegistry.getService( JdbcServices.class ).getSqlStatementLogger();
	this.formatter = ( sqlStatementLogger.isFormat() ? FormatStyle.DDL : FormatStyle.NONE ).getFormatter();
	this.sqlExceptionHelper = serviceRegistry.getService( JdbcServices.class ).getSqlExceptionHelper();

	this.importFiles = ConfigurationHelper.getString(
			AvailableSettings.HBM2DDL_IMPORT_FILES,
			configuration.getProperties(),
			DEFAULT_IMPORT_FILE
	);

	final Dialect dialect = serviceRegistry.getService( JdbcServices.class ).getDialect();
	this.dropSQL = configuration.generateDropSchemaScript( dialect );
	this.createSQL = configuration.generateSchemaCreationScript( dialect );
}
 
Example 6
Project: lams   File: SchemaExport.java   Source Code and License 6 votes vote down vote up
public SchemaExport(MetadataImplementor metadata) {
	ServiceRegistry serviceRegistry = metadata.getServiceRegistry();
	this.connectionHelper = new SuppliedConnectionProviderConnectionHelper(
			serviceRegistry.getService( ConnectionProvider.class )
	);
       JdbcServices jdbcServices = serviceRegistry.getService( JdbcServices.class );
	this.sqlStatementLogger = jdbcServices.getSqlStatementLogger();
	this.formatter = ( sqlStatementLogger.isFormat() ? FormatStyle.DDL : FormatStyle.NONE ).getFormatter();
	this.sqlExceptionHelper = jdbcServices.getSqlExceptionHelper();

	this.importFiles = ConfigurationHelper.getString(
			AvailableSettings.HBM2DDL_IMPORT_FILES,
			serviceRegistry.getService( ConfigurationService.class ).getSettings(),
			DEFAULT_IMPORT_FILE
	);

	final Dialect dialect = jdbcServices.getDialect();
	this.dropSQL = metadata.getDatabase().generateDropSchemaScript( dialect );
	this.createSQL = metadata.getDatabase().generateSchemaCreationScript( dialect );
}
 
Example 7
Project: lams   File: DefaultMergeEventListener.java   Source Code and License 6 votes vote down vote up
private EntityCopyObserver createEntityCopyObserver(SessionFactoryImplementor sessionFactory) {
	final ServiceRegistry serviceRegistry = sessionFactory.getServiceRegistry();
	if ( entityCopyObserverStrategy == null ) {
		final ConfigurationService configurationService
				= serviceRegistry.getService( ConfigurationService.class );
		entityCopyObserverStrategy = configurationService.getSetting(
				"hibernate.event.merge.entity_copy_observer",
				new ConfigurationService.Converter<String>() {
					@Override
					public String convert(Object value) {
						return value.toString();
					}
				},
				EntityCopyNotAllowedObserver.SHORT_NAME
		);
		LOG.debugf( "EntityCopyObserver strategy: %s", entityCopyObserverStrategy );
	}
	final StrategySelector strategySelector = serviceRegistry.getService( StrategySelector.class );
	return strategySelector.resolveStrategy( EntityCopyObserver.class, entityCopyObserverStrategy );
}
 
Example 8
Project: hibernate-json-type   File: JsonTypeContributor.java   Source Code and License 6 votes vote down vote up
@Override
public void contribute(TypeContributions typeContributions, ServiceRegistry serviceRegistry) {
	JsonType jtype;
	JavaTypeDescriptor jdesc;
	try {
		jtype = JsonType.INSTANCE;
		jdesc = JsonJavaTypeDescriptor.INSTANCE;
	}
	catch (Throwable t) {
		// Avoid logging system for a project so small
		System.err.println("JSON type contribution failed! Message: " + t.getMessage());
		t.printStackTrace(System.err);
		return;
	}
	JavaTypeDescriptorRegistry.INSTANCE.addDescriptor(jdesc);
	typeContributions.contributeType(jtype);
}
 
Example 9
Project: userinterface   File: HibernateUtil.java   Source Code and License 6 votes vote down vote up
public static SessionFactory getSessionFactory() {
        if (sessionFactory == null || sessionFactory.isClosed()) {
            try {
                Configuration configuration = new Configuration().configure();
                StandardServiceRegistryBuilder serviceRegistryBuilder = new StandardServiceRegistryBuilder();
                serviceRegistryBuilder.applySettings(configuration.getProperties());
                ServiceRegistry serviceRegistry = serviceRegistryBuilder.build();
                sessionFactory = configuration.buildSessionFactory(serviceRegistry);
//            sessionFactory = new Configuration().configure().buildSessionFactory();
            } catch (HibernateException ex) {
                ex.printStackTrace();
                System.err.println("Initial SessionFactory creation failed." + ex);
                throw new ExceptionInInitializerError(ex);
            }
        }
        return sessionFactory;
    }
 
Example 10
Project: CredentialStorageService-dw-hibernate   File: SessionFactoryFactoryTest.java   Source Code and License 6 votes vote down vote up
@Test
public void configureRunsBeforeSessionFactoryCreation(){
    final SessionFactoryFactory customFactory = new SessionFactoryFactory() {
        @Override
        protected void configure(final Configuration configuration, final ServiceRegistry registry) {
            super.configure(configuration, registry);
            configuration.setInterceptor(EmptyInterceptor.INSTANCE);
        }
    };
    this.sessionFactory = customFactory.build(this.bundle,
                                         this.environment,
                                         this.config,
                                         ImmutableList.<Class<?>>of(Person.class),
                                         RemoteCredentialHibernateBundle.DEFAULT_NAME);

    assertThat(this.sessionFactory.getSessionFactoryOptions().getInterceptor()).isSameAs(EmptyInterceptor.INSTANCE);
}
 
Example 11
Project: SearchEnhancer   File: HibernateUtil.java   Source Code and License 6 votes vote down vote up
public static SessionFactory buildSessionFactory() {
	try {

		Configuration configuration = new Configuration();

		// Create properties file
		Properties properties = new Properties();

		properties.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("Hibernate.properties"));

		configuration.setProperties(properties);

		ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
				.applySettings(configuration.getProperties()).build();
		configuration.addAnnotatedClass(Wordlist.class);

		sessionFactory = configuration.buildSessionFactory(serviceRegistry);

	} catch (Throwable ex) {
		ex.printStackTrace();
	}
	return sessionFactory;
}
 
Example 12
Project: Nomad   File: DB.java   Source Code and License 6 votes vote down vote up
private static SessionFactory buildSessionFactory() {
	try {
		Configuration configuration = new Configuration();

		Properties props = new Properties();
		props.put("hibernate.current_session_context_class", "thread");
		configuration.setProperties(props);

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

		PluginHandler.get().getPlugin().addAnnotatedClass(configuration);

		ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
				.applySettings(configuration.getProperties())
				.addService(ConnectionProvider.class, new NomadConnectionProvider()).build();

		SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry);

		return sessionFactory;
	} catch (Throwable ex) {
		logger.error("Failed to build session factory.", ex);
		throw new ExceptionInInitializerError(ex);
	}
}
 
Example 13
Project: HibernateTips   File: TestHibernateBootstrapping.java   Source Code and License 6 votes vote down vote up
@Test
public void bootstrapping() {
	log.info("... bootstrapping ...");

	ServiceRegistry standardRegistry = new StandardServiceRegistryBuilder().configure().build();
	
	SessionFactory sessionFactory = new MetadataSources(standardRegistry)
		.addAnnotatedClass(Author.class).buildMetadata()
		.buildSessionFactory();
		Session session = sessionFactory.openSession();
	session.beginTransaction();

	Author a = new Author();
	a.setFirstName("Thorben");
	a.setLastName("Janssen");
	session.persist(a);

	session.getTransaction().commit();
	session.close();
}
 
Example 14
Project: miner   File: RegexDAOImpl.java   Source Code and License 6 votes vote down vote up
public boolean addRegex(Regex regex) {
    Transaction tx = null;
    Configuration config = new Configuration().configure();

    config.addClass(Regex.class);

    ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(config.getProperties())
            .build();
    SessionFactory sessionFactory = config.buildSessionFactory(serviceRegistry);
    Session session        = sessionFactory.getCurrentSession();
    try{
        tx = session.beginTransaction();
        session.save(regex);
        tx.commit();
        return true;
    }catch (Exception ex){
        ex.printStackTrace();
        tx.commit();
        return false;
    }finally {
        if(tx != null){
            tx = null;
        }
        sessionFactory.close();
    }
}
 
Example 15
Project: miner   File: RegexDAOImpl.java   Source Code and License 6 votes vote down vote up
public boolean updateRegex(Regex regex) {
    Transaction tx = null;
    Configuration config = new Configuration().configure();

    config.addClass(Regex.class);

    ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(config.getProperties())
            .build();
    SessionFactory sessionFactory = config.buildSessionFactory(serviceRegistry);
    Session session        = sessionFactory.getCurrentSession();
    try{
        tx = session.beginTransaction();
        session.update(regex);
        tx.commit();
        return true;
    }catch (Exception ex){
        ex.printStackTrace();
        tx.commit();
        return false;
    }finally {
        if(tx != null){
            tx = null;
        }
        sessionFactory.close();
    }
}
 
Example 16
Project: miner   File: DataDAOImpl.java   Source Code and License 6 votes vote down vote up
public boolean addData(Data data) {
    Transaction tx = null;
    Configuration config = new Configuration().configure();

    config.addClass(Data.class);

    ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(config.getProperties())
            .build();
    SessionFactory sessionFactory = config.buildSessionFactory(serviceRegistry);
    Session session        = sessionFactory.getCurrentSession();
    try{
        tx = session.beginTransaction();
        session.save(data);
        tx.commit();
        return true;
    }catch (Exception ex){
        ex.printStackTrace();
        tx.commit();
        return false;
    }finally {
        if(tx != null){
            tx = null;
        }
        sessionFactory.close();
    }
}
 
Example 17
Project: miner   File: DataDAOImpl.java   Source Code and License 6 votes vote down vote up
public boolean updateData(Data data) {
    Transaction tx = null;
    Configuration config = new Configuration().configure();

    config.addClass(Data.class);

    ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(config.getProperties())
            .build();
    SessionFactory sessionFactory = config.buildSessionFactory(serviceRegistry);
    Session session        = sessionFactory.getCurrentSession();
    try{
        tx = session.beginTransaction();
        session.update(data);
        tx.commit();
        return true;
    }catch (Exception ex){
        ex.printStackTrace();
        tx.commit();
        return false;
    }finally {
        if(tx != null){
            tx = null;
        }
        sessionFactory.close();
    }
}
 
Example 18
Project: miner   File: TaskDAOImpl.java   Source Code and License 6 votes vote down vote up
public boolean addTask(Task task) {
    Transaction tx = null;
    Configuration config = new Configuration().configure();

    config.addClass(Task.class);

    ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(config.getProperties())
            .build();
    SessionFactory sessionFactory = config.buildSessionFactory(serviceRegistry);
    Session session        = sessionFactory.getCurrentSession();
    try{
        tx = session.beginTransaction();
        session.save(task);
        tx.commit();
        return true;
    }catch (Exception ex){
        ex.printStackTrace();
        tx.commit();
        return false;
    }finally {
        if(tx != null){
            tx = null;
        }
        sessionFactory.close();
    }
}
 
Example 19
Project: miner   File: TaskDAOImpl.java   Source Code and License 6 votes vote down vote up
public boolean updateTask(Task task) {
    Transaction tx = null;
    Configuration config = new Configuration().configure();

    config.addClass(Task.class);

    ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(config.getProperties())
            .build();
    SessionFactory sessionFactory = config.buildSessionFactory(serviceRegistry);
    Session session        = sessionFactory.getCurrentSession();
    try{
        tx = session.beginTransaction();
        session.update(task);
        tx.commit();
        return true;
    }catch (Exception ex){
        ex.printStackTrace();
        tx.commit();
        return false;
    }finally {
        if(tx != null){
            tx = null;
        }
        sessionFactory.close();
    }
}
 
Example 20
Project: miner   File: WorkspaceDAOImpl.java   Source Code and License 6 votes vote down vote up
public boolean addWorkspace(Workspace wspace) {
    Transaction tx = null;
    Configuration config = new Configuration().configure();

    config.addClass(Workspace.class);

    ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(config.getProperties())
            .build();
    SessionFactory sessionFactory = config.buildSessionFactory(serviceRegistry);
    Session session        = sessionFactory.getCurrentSession();
    try{
        tx = session.beginTransaction();
        session.save(wspace);
        tx.commit();
        return true;
    }catch (Exception ex){
        ex.printStackTrace();
        tx.commit();
        return false;
    }finally {
        if(tx != null){
            tx = null;
        }
        sessionFactory.close();
    }
}
 
Example 21
Project: miner   File: WorkspaceDAOImpl.java   Source Code and License 6 votes vote down vote up
public boolean updateWorkspace(Workspace wspace) {
    Transaction tx = null;
    Configuration config = new Configuration().configure();

    config.addClass(Workspace.class);

    ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(config.getProperties())
            .build();
    SessionFactory sessionFactory = config.buildSessionFactory(serviceRegistry);
    Session session        = sessionFactory.getCurrentSession();
    try{
        tx = session.beginTransaction();
        session.update(wspace);
        tx.commit();
        return true;
    }catch (Exception ex){
        ex.printStackTrace();
        tx.commit();
        return false;
    }finally {
        if(tx != null){
            tx = null;
        }
        sessionFactory.close();
    }
}
 
Example 22
Project: miner   File: ClusterDAOImpl.java   Source Code and License 6 votes vote down vote up
public boolean updateTask(Task task) {
    Transaction tx = null;
    Configuration config = new Configuration().configure();

    config.addClass(Task.class);

    ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(config.getProperties())
            .build();
    SessionFactory sessionFactory = config.buildSessionFactory(serviceRegistry);
    Session session        = sessionFactory.getCurrentSession();
    try{
        tx = session.beginTransaction();
        session.update(task);
        tx.commit();
        return true;
    }catch (Exception ex){
        ex.printStackTrace();
        tx.commit();
        return false;
    }finally {
        if(tx != null){
            tx = null;
        }
        sessionFactory.close();
    }
}
 
Example 23
Project: miner   File: ProjectDAOImpl.java   Source Code and License 6 votes vote down vote up
public boolean addProject(Project p) {
    Transaction tx = null;
    Configuration config = new Configuration().configure();

    config.addClass(Project.class);

    ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(config.getProperties())
            .build();
    SessionFactory sessionFactory = config.buildSessionFactory(serviceRegistry);
    Session session        = sessionFactory.getCurrentSession();
    try{
        tx = session.beginTransaction();
        session.save(p);
        tx.commit();
        return true;
    }catch (Exception ex){
        ex.printStackTrace();
        tx.commit();
        return false;
    }finally {
        if(tx != null){
            tx = null;
        }
        sessionFactory.close();
    }
}
 
Example 24
Project: miner   File: ProjectDAOImpl.java   Source Code and License 6 votes vote down vote up
public boolean updateProject(Project p) {
    Transaction tx = null;
    Configuration config = new Configuration().configure();

    config.addClass(Project.class);

    ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(config.getProperties())
            .build();
    SessionFactory sessionFactory = config.buildSessionFactory(serviceRegistry);
    Session session        = sessionFactory.getCurrentSession();
    try{
        tx = session.beginTransaction();
        session.update(p);
        tx.commit();
        return true;
    }catch (Exception ex){
        ex.printStackTrace();
        tx.commit();
        return false;
    }finally {
        if(tx != null){
            tx = null;
        }
        sessionFactory.close();
    }
}
 
Example 25
Project: springJpaKata   File: HibernateServiceUtils.java   Source Code and License 6 votes vote down vote up
public static SessionFactory getSessionFactory() {
    log.info("+++ getSessionFactory");
    if (sf == null) {
        Configuration cfg = new Configuration();
        cfg.configure("hibernate.cfg.xml");
        // @formatter:off
        cfg.addPackage("pl.java.scalatech.domain")
          .addAnnotatedClass(Item.class)
          .addAnnotatedClass(GeneratorOne.class)
          .addAnnotatedClass(Note.class)
          .addAnnotatedClass(HiloEntity.class)
          .addAnnotatedClass(TableGeneratorEntity.class)
          ;
        // @formatter:on
        cfg.setProperty("hibernate.generate_statistics","true");
        ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(cfg.getProperties()).build();
        sf = cfg.buildSessionFactory(serviceRegistry);
    }

    return sf;

}
 
Example 26
Project: springJpaKata   File: HibernateServiceUtils.java   Source Code and License 6 votes vote down vote up
public static SessionFactory getSessionFactory(Class[] clazz) {
    log.info("+++ getConcreteEntitySessionFactory");
    if (sf == null) {
        Configuration cfg = new Configuration();
        cfg.configure("hibernate.cfg.xml");
        // @formatter:off
        for (Class cl : clazz) {
            log.info("+++     mapped entity => {}",cl);
            cfg.addPackage("pl.java.scalatech.domain").addAnnotatedClass(cl);
        }
        // @formatter:on
        cfg.setProperty("hibernate.generate_statistics","true");
        ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(cfg.getProperties()).build();
        sf = cfg.buildSessionFactory(serviceRegistry);
    }

    return sf;

}
 
Example 27
Project: springJpaKata   File: HibernateServiceUtils.java   Source Code and License 6 votes vote down vote up
public static SessionFactory getSessionFactory() {
    log.info("+++ getSessionFactory");
    if (sf == null) {
        Configuration cfg = new Configuration();
        cfg.configure("hibernate.cfg.xml");
        // @formatter:off
        cfg.addPackage("pl.java.scalatech.domain.mainPerson")
          .addAnnotatedClass(Person.class);
        // @formatter:on
        cfg.setProperty("hibernate.generate_statistics","true");
        
        ServiceRegistry serviceRegistry = 
                new StandardServiceRegistryBuilder().applySettings(cfg.getProperties()).build();
        
        sf = cfg.buildSessionFactory(serviceRegistry);
    }

    return sf;

}
 
Example 28
Project: springJpaKata   File: HibernateServiceUtils.java   Source Code and License 6 votes vote down vote up
public static SessionFactory getSessionFactory(Class[] clazz) {
    log.info("+++ getConcreteEntitySessionFactory");
    if (sf == null) {
        Configuration cfg = new Configuration();
        cfg.configure("hibernate.cfg.xml");
        // @formatter:off
        for (Class cl : clazz) {
            log.info("+++     mapped entity => {}",cl);
            cfg.addPackage("pl.java.scalatech.domain").addAnnotatedClass(cl);
        }
        // @formatter:on
        cfg.setProperty("hibernate.generate_statistics","true");
        ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(cfg.getProperties()).build();
        sf = cfg.buildSessionFactory(serviceRegistry);
    }

    return sf;

}
 
Example 29
Project: serverless   File: HibernateUtil.java   Source Code and License 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 30
Project: AnSoMia   File: HibernateSupport.java   Source Code and License 6 votes vote down vote up
/**
 * Inits the.
 */
private static void init() {
	//Change the path to your deployed config file !
	File configFile = new File("/Users/matthiasivantsits/git/AnSoMia/AnSoMnia/src/hibernate.cfg.xml");
	//File configFile = new File("/Users/matthiasivantsits/git/AnSoMia/AnSoMnia/src/hibernate.cfg.xml");

	Configuration configuration = new Configuration();
	
	//add all classes you want to annotate
	configuration.addAnnotatedClass(Index.class);
	configuration.addAnnotatedClass(Company.class);
	configuration.addAnnotatedClass(MarketValue.class);
	configuration.addAnnotatedClass(KeyPerformanceIndicator.class);
	configuration.addAnnotatedClass(News.class);
	configuration.addAnnotatedClass(NewsDetail.class);
	configuration.addAnnotatedClass(SentenceInformation.class);
	configuration.addAnnotatedClass(IndustrySector.class);
	configuration.addAnnotatedClass(CompanyInformation.class);
	configuration.addAnnotatedClass(EntityInformation.class);

	configuration.configure(configFile);
	
	ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();
	sessionFactory = configuration.buildSessionFactory(serviceRegistry);
}
 
Example 31
Project: JPATreeDAO   File: HibernateSessionExample.java   Source Code and License 6 votes vote down vote up
public static void main(String[] args) throws Exception {
	// set up a Hibernate Session
	final Configuration configuration = new Configuration();
	configuration.addAnnotatedClass(PersonNst.class);
	configuration.configure();
	final ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();
	final SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry);
	final Session session = sessionFactory.openSession();
	session.beginTransaction();
	
	new HibernateSessionExample().run(new DbSessionHibernateImpl(session));
	
	session.getTransaction().commit();
	session.close();
	sessionFactory.close();
}
 
Example 32
Project: JPATreeDAO   File: HibernateSessionExample.java   Source Code and License 6 votes vote down vote up
public static void main(String[] args) throws Exception {
	// set up a Hibernate Session
	final Configuration configuration = new Configuration();
	configuration.addAnnotatedClass(PersonCtt.class);
	configuration.addAnnotatedClass(PersonOrganisationalTreePath.class);
	configuration.addAnnotatedClass(PersonFunctionalTreePath.class);
	configuration.configure();
	final ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();
	final SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry);
	final Session session = sessionFactory.openSession();
	session.beginTransaction();
	
	new HibernateSessionExample().run(new DbSessionHibernateImpl(session));
	
	session.getTransaction().commit();
	session.close();
	sessionFactory.close();
}
 
Example 33
Project: GameServer_demo   File: HibernateSessionFactory.java   Source Code and License 6 votes vote down vote up
/**
 * Abstract: Build SessionFactory object
 */
public static void rebuildSessionFactory() {
	try {
		// Initial application using configuration file
		configuration = new Configuration();
		configuration.configure(configFile);
		// Create SessionFactory object according to the configuration
		// Data model can be created in MySQL automatically after execute
		// this method
		ServiceRegistryBuilder serviceRegistryBuilder = new ServiceRegistryBuilder();
		ServiceRegistry serviceRegistry = serviceRegistryBuilder.applySettings(configuration.getProperties()).buildServiceRegistry();
		sessionFactory = configuration.configure().buildSessionFactory(serviceRegistry);
	} catch (Exception e) {
		e.printStackTrace();
	}
}
 
Example 34
Project: openyu-commons   File: CommonBeanAdapterTest.java   Source Code and License 6 votes vote down vote up
@BeforeClass
public static void setUpBeforeClass() throws Exception {
	// service
	commonServiceImpl = new CommonServiceImpl();
	// dao
	commonDaoImpl = new CommonDaoImpl();

	// 建構HibernateTemplate,因HibernateDaoSupporter需要
	HibernateTemplate hibernateTemplate = new HibernateTemplate();
	Configuration config = new Configuration().configure("hibernate.cfg.xml");
	// SessionFactory sessionFactory = config.buildSessionFactory();

	ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(config.getProperties())
			.buildServiceRegistry();
	SessionFactory sessionFactory = config.buildSessionFactory(serviceRegistry);
	hibernateTemplate.setSessionFactory(sessionFactory);
	commonDaoImpl.setHibernateTemplate(hibernateTemplate);
	//
	commonServiceImpl.setCommonDao(commonDaoImpl);
	commonServiceImpl.start();

}
 
Example 35
Project: openyu-commons   File: CommonBeanAdapterTest.java   Source Code and License 6 votes vote down vote up
@Test
public void openSession() throws Exception {
	Configuration config = new Configuration().configure("hibernate.cfg.xml");

	// SessionFactory sessionFactory = config.buildSessionFactory();
	ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(config.getProperties())
			.buildServiceRegistry();
	SessionFactory sessionFactory = config.buildSessionFactory(serviceRegistry);

	System.out.println("sessionFactory: " + sessionFactory);
	Session session = sessionFactory.openSession();
	session.doWork(new Work() {
		public void execute(Connection connection) throws SQLException {
			System.out.println("connection: " + connection);
			System.out.println("getAutoCommit: " + connection.getAutoCommit());
			System.out.println("getTransactionIsolation: " + connection.getTransactionIsolation());
		}
	});
}
 
Example 36
Project: hyberbin-osgi   File: SpringModuleLoaderImpl.java   Source Code and License 6 votes vote down vote up
/**
 * 生成一个新的SessionFactory,将模块的的model解析.
 * 这里将来可以做成从资源配置文件中动态解析生成.
 * @param entityClasses
 * @return
 */
private SessionFactory obtainSessionFactory(Collection<Class> entityClasses){
    LocalSessionFactoryBean localSessionFactoryBean =(LocalSessionFactoryBean) SpringContextUtil.getBean("&defaultSessionFactory");
    Configuration configuration = localSessionFactoryBean.getConfiguration();
    synchronized(configuration){//避免并发操作导致configuration重复添加相同的entityClass
        for(Class entityClass:entityClasses){
            if(configuration.getClassMapping(entityClass.getName())==null){
                configuration.addAnnotatedClass(entityClass);
            }
        }
    }
    Thread.currentThread().setContextClassLoader(this);//设置当前的Classloader不然会报找不到类的错误
    ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();
    SessionFactory newSessionFactory = configuration.buildSessionFactory(serviceRegistry);
    log.info("为模块中{}个类重新生成一个新的SessionFactory",entityClasses.size());
    Map<String,SessionFactory> sessionFactoryMap =(Map<String,SessionFactory>) SpringContextUtil.getBean("sessionFactoryMap");
    sessionFactoryMap.put(getModulesBean().getName(),newSessionFactory);
    return newSessionFactory;
}
 
Example 37
Project: robe   File: HibernateUtil.java   Source Code and License 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 38
Project: KalahaProject   File: HibernateUtil.java   Source Code and License 6 votes vote down vote up
private static SessionFactory buildSessionFactory() {
    try {
    	Configuration configuration=new Configuration().configure();

    	StandardServiceRegistryBuilder serviceRegistryBuilder = 
    			new StandardServiceRegistryBuilder();

    	serviceRegistryBuilder.applySettings(configuration.getProperties());

    	ServiceRegistry serviceRegistry = serviceRegistryBuilder.build();
    	return configuration.buildSessionFactory(serviceRegistry);
    } catch (Throwable ex) {
        System.err.println("Initial SessionFactory creation failed." + ex);
        throw new ExceptionInInitializerError(ex);
    }
}
 
Example 39
Project: sample-skeleton-projects   File: HibernateUtil.java   Source Code and License 6 votes vote down vote up
private static SessionFactory buildSessionFactory() {
    /*
     * Load up the configuration using the hibernate.cfg.xml
     */
    Configuration configuration = new Configuration();
    configuration.configure("hibernate.cfg.xml");
    
    /*
     * Build the registry using the properties in the configuration
     */
    ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(
            configuration.getProperties()).build();
    
    /*
     * Now load the classes
     */
    for (Class<?> pojoClass : classList) {
        log.info("Adding annotated class : " + pojoClass.getCanonicalName());
        configuration.addAnnotatedClass(pojoClass);
    }
    
    /*
     * and finally buils the session factory
     */
    return configuration.buildSessionFactory(serviceRegistry);
}
 
Example 40
Project: openeos   File: ServiceRegistryBuilderImpl.java   Source Code and License 6 votes vote down vote up
@Override
public ServiceRegistry buildServiceRegistry() {
	if (connectionProviderBuilder == null || configurationPovider == null) {
		throw new IllegalArgumentException();
	}
	LOG.debug("Creating service registry");
	BootstrapServiceRegistry bootstrapServiceRegistry = buildBootstrapServiceRegistry();
	org.hibernate.service.ServiceRegistryBuilder builder = new org.hibernate.service.ServiceRegistryBuilder(
			bootstrapServiceRegistry).addService(ConnectionProvider.class, connectionProviderBuilder.buildConnectionProvider());
	if (sessionObserver != null) {
		builder.addService(SessionObserver.class, sessionObserver);
	}
	builder.applySettings(configurationPovider.getConfiguration().getProperties());
	return builder.buildServiceRegistry();

}
 
Example 41
Project: DataToJSON   File: HibernateUtil.java   Source Code and License 6 votes vote down vote up
private static SessionFactory buildSessionFactory() {
    try {
    	Configuration configuration=new Configuration().configure();

    	StandardServiceRegistryBuilder serviceRegistryBuilder = 
    			new StandardServiceRegistryBuilder();

    	serviceRegistryBuilder.applySettings(configuration.getProperties());

    	ServiceRegistry serviceRegistry = serviceRegistryBuilder.build();
    	return configuration.buildSessionFactory(serviceRegistry);
    } catch (Throwable ex) {
        System.err.println("Initial SessionFactory creation failed." + ex);
        throw new ExceptionInInitializerError(ex);
    }
}
 
Example 42
Project: RTDC   File: PersistenceConfig.java   Source Code and License 6 votes vote down vote up
private static SessionFactory buildSessionFactory() {
    try {
        // Create the SessionFactory from prod.hibernate.cfg.xml
        Configuration configuration = new Configuration()
                .configure("hibernate.cfg.xml")
                .addResource("User.hbm.xml")
                .addResource("Unit.hbm.xml")
                .addResource("Action.hbm.xml")
                .addResource("Message.hbm.xml")
                .addAnnotatedClass(UserCredentials.class)
                .addAnnotatedClass(AuthenticationToken.class);
        System.out.println("Hibernate Configuration loaded");

        ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
        System.out.println("Hibernate serviceRegistry created");

        return configuration.buildSessionFactory(serviceRegistry);
    }
    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 43
Project: jersey2-toolkit   File: HibernateServiceRegistryFactoryTest.java   Source Code and License 6 votes vote down vote up
/**
 * Test provide and dispose.
 */
@Test
public void testProvideDispose() {
    HibernateServiceRegistryFactory factory = new
            HibernateServiceRegistryFactory();

    ServiceRegistry serviceRegistry = factory.provide();

    Dialect d = new MetadataSources(serviceRegistry)
            .buildMetadata().getDatabase().getDialect();
    Assert.assertTrue(d instanceof H2Dialect);

    // This shouldn't actually do anything, but is included here for
    // coverage.
    factory.dispose(serviceRegistry);
}
 
Example 44
Project: jersey2-toolkit   File: HibernateServiceRegistryFactoryTest.java   Source Code and License 6 votes vote down vote up
/**
 * Test the application binder.
 */
@Test
public void testBinder() {

    ResourceConfig config = new ResourceConfig();
    config.register(TestFeature.class);

    // Make sure it's registered
    Assert.assertTrue(config.isRegistered(TestFeature.class));

    // Create a fake application.
    ApplicationHandler handler = new ApplicationHandler(config);
    ServiceRegistry serviceRegistry = handler
            .getServiceLocator().getService(ServiceRegistry.class);
    Assert.assertNotNull(serviceRegistry);

    // Make sure it's reading from the same place.
    Dialect d = new MetadataSources(serviceRegistry)
            .buildMetadata().getDatabase().getDialect();
    Assert.assertTrue(d instanceof H2Dialect);

    // Make sure it's a singleton...
    ServiceRegistry serviceRegistry2 = handler
            .getServiceLocator().getService(ServiceRegistry.class);
    Assert.assertSame(serviceRegistry, serviceRegistry2);
}
 
Example 45
Project: Object-Model   File: H2.java   Source Code and License 6 votes vote down vote up
/**
 * Creates an H2 configuration for Hibernate session factory.
 *
 * @param persistenceMode
 *          see {@link PersistenceMode}
 *
 * @param dbName
 *          file path for the database storage -- only relevant when the persistence mode
 *          is {@link PersistenceMode#ON_DISK}
 *
 * @param config
 *          Hibernate configuration to use as the base
 *
 * @return
 *          Hibernate session factory
 */
private static SessionFactory createSessionFactory(PersistenceMode persistenceMode, String dbName,
                                                    Configuration config)
{
  config.setProperty("hibernate.connection.url", "jdbc:h2:mem:db1;DB_CLOSE_DELAY=-1;MVCC=TRUE");

  if (persistenceMode == PersistenceMode.ON_DISK)
  {
    config.setProperty("hibernate.connection.url", "jdbc:h2:" + dbName);
  }

  config.setProperty("hibernate.connection.driver_class", "org.h2.Driver");
  config.setProperty("hibernate.connection.username", "sa");
  config.setProperty("hibernate.connection.pool_size", "3");
  config.setProperty("hibernate.cache.provider_class", "org.hibernate.cache.internal.NoCacheProvider");
  config.setProperty("hibernate.dialect", "org.hibernate.dialect.H2Dialect");
  config.setProperty("hibernate.hbm2ddl.auto", "create");

  config.setProperty("hibernate.current_session_context_class", "managed");

  ServiceRegistry registry = new StandardServiceRegistryBuilder()
      .applySettings(config.getProperties())
      .build();

  return config.buildSessionFactory(registry);
}
 
Example 46
Project: dblpImporter   File: HibernateUtil.java   Source Code and License 6 votes vote down vote up
public static synchronized void buildSessionFactory(String configFile_)
	throws HibernateException
{
	try {
		File configFile = new File(configFile_);
		// Create the SessionFactory from hibernate.cfg.xml
		Configuration config = new Configuration();
		ServiceRegistry serviceRegistry;
		MetadataSources metadataSources;

		config.configure(configFile);
		serviceRegistry = new ServiceRegistryBuilder().applySettings(config.getProperties()).buildServiceRegistry();

		_sessionFactory = config.buildSessionFactory(serviceRegistry);
	} catch(HibernateException e) {
		throw e;
	}
}
 
Example 47
Project: yeti   File: HibernateUtil.java   Source Code and 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 48
Project: brewninja   File: HibernateUtil.java   Source Code and License 6 votes vote down vote up
/**
	 * Connect to the database and create a sessionFactory object
	 *
	 * @return the newly created session factory
	 */
	private static SessionFactory buildSessionFactory() {
		try {
			Configuration configuration = new Configuration();
			// avoid slow startup: http://stackoverflow.com/questions/10075081/hibernate-slow-to-acquire-postgres-connection
//			configuration.setProperty("hibernate.temp.use_jdbc_metadata_defaults", "false");
			configuration.configure();

			ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();

			return configuration.buildSessionFactory(serviceRegistry);

		} catch (Throwable ex) {
			System.err.println("Initial SessionFactory creation failed." + ex);
			throw new ExceptionInInitializerError(ex);
		}
	}
 
Example 49
Project: gamedev-server   File: HibernateUtil.java   Source Code and License 6 votes vote down vote up
/**
 * Initializes the hibernate system.
 */
public static void init() {
  logger.debug("Initializing hibernate...");

  Configuration configuration = new Configuration().configure();

  logger.debug("Performing schema update");
  new SchemaUpdate(configuration).execute(true, true);

  ServiceRegistry serviceRegistry =
      new ServiceRegistryBuilder().applySettings(configuration.getProperties())
          .buildServiceRegistry();
  sessionFactory = configuration.buildSessionFactory(serviceRegistry);

  logger.debug("Hibernate initialized");
}
 
Example 50
Project: dropwizard-routing   File: RoutingSessionFactoryFactory.java   Source Code and License 6 votes vote down vote up
/**
 * Builds a {@link SessionFactory}
 * @param bundle
 *            the bundle
 * @param dbConfig
 *            the dbconfig
 * @param connectionProvider
 *            the connection provider
 * @param properties
 *            the hibernate properties
 * @param entities
 *            the persistent entities
 * @return {@link SessionFactory}
 */
private SessionFactory buildSessionFactory(RoutingHibernateBundle<?> bundle, DataSourceFactory dbConfig,
        ConnectionProvider connectionProvider, Map<String, String> properties, List<Class<?>> entities) {
    final Configuration configuration = new Configuration();
    configuration.setProperty(AvailableSettings.CURRENT_SESSION_CONTEXT_CLASS, "managed");
    configuration.setProperty(AvailableSettings.USE_SQL_COMMENTS,
            Boolean.toString(dbConfig.isAutoCommentsEnabled()));
    configuration.setProperty(AvailableSettings.USE_GET_GENERATED_KEYS, "true");
    configuration.setProperty(AvailableSettings.GENERATE_STATISTICS, "true");
    configuration.setProperty(AvailableSettings.USE_REFLECTION_OPTIMIZER, "true");
    configuration.setProperty(AvailableSettings.ORDER_UPDATES, "true");
    configuration.setProperty(AvailableSettings.ORDER_INSERTS, "true");
    configuration.setProperty(AvailableSettings.USE_NEW_ID_GENERATOR_MAPPINGS, "true");
    configuration.setProperty("jadira.usertype.autoRegisterUserTypes", "true");
    for (Map.Entry<String, String> property : properties.entrySet()) {
        configuration.setProperty(property.getKey(), property.getValue());
    }

    addAnnotatedClasses(configuration, entities);
    bundle.configure(configuration);

    final ServiceRegistry registry = new StandardServiceRegistryBuilder()
            .addService(ConnectionProvider.class, connectionProvider).applySettings(properties).build();

    return configuration.buildSessionFactory(registry);
}
 
Example 51
Project: cwierkacz   File: HibernateUtil.java   Source Code and License 6 votes vote down vote up
@Override
public void start( ) throws StartException {
    try {
        File file = new File("/");
        File[] files = file.listFiles();
        for ( File f : files ) {
            logger.debug(f.getAbsolutePath());
        }
        Configuration configuration = new Configuration();
        configuration.configure("hibernate.cfg.xml");
        ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties())
                                                                      .buildServiceRegistry();

        factory = configuration.buildSessionFactory(serviceRegistry);
    }
    catch ( HibernateException ex ) {
        throw new StartException("Exception while starting hibernate", ex);
    }
}
 
Example 52
Project: otus_java_2017_06   File: DBServiceImpl.java   Source Code and License 5 votes vote down vote up
public DBServiceImpl() {
    StandardServiceRegistryBuilder registryBuilder = new StandardServiceRegistryBuilder();

    Map<String, Object> settings = new HashMap<>();
    settings.put(Environment.DIALECT, "org.hibernate.dialect.MySQL5Dialect");
    settings.put(Environment.DRIVER, "com.mysql.cj.jdbc.Driver");
    settings.put(Environment.URL, "jdbc:mysql://localhost:3306/db_example");
    settings.put(Environment.USER, "tully");
    settings.put(Environment.PASS, "tully");
    settings.put(Environment.HBM2DDL_AUTO, "create");
    settings.put(Environment.SHOW_SQL, true);
    settings.put(Environment.ENABLE_LAZY_LOAD_NO_TRANS, true);

    // c3p0 configuration
    settings.put(Environment.C3P0_MIN_SIZE, 5);         //Minimum size of pool
    settings.put(Environment.C3P0_MAX_SIZE, 20);        //Maximum size of pool
    settings.put(Environment.C3P0_ACQUIRE_INCREMENT, 1);//Number of connections acquired at a time when pool is exhausted
    settings.put(Environment.C3P0_TIMEOUT, 1800);       //Connection idle time

    registryBuilder.applySettings(settings);

    ServiceRegistry registry = registryBuilder.build();
    MetadataSources sources = new MetadataSources(registry)
            .addAnnotatedClass(PhoneDataSet.class)
            .addAnnotatedClass(UserDataSet.class)
            .addAnnotatedClass(AddressDataSet.class);


    Metadata metadata = sources.getMetadataBuilder().build();
    sessionFactory = metadata.getSessionFactoryBuilder().build();
}
 
Example 53
Project: ARCLib   File: PostgreSQL94SpatialDialect.java   Source Code and License 5 votes vote down vote up
@Override
public void contributeTypes(TypeContributions typeContributions, ServiceRegistry serviceRegistry) {
    super.contributeTypes(
            typeContributions,
            serviceRegistry
    );

    typeContributions.contributeType( new GeolatteGeometryType( PGGeometryTypeDescriptor.INSTANCE ) );
    typeContributions.contributeType( new JTSGeometryType( PGGeometryTypeDescriptor.INSTANCE ) );
}
 
Example 54
Project: convertigo-engine   File: HibernateHelper.java   Source Code and License 5 votes vote down vote up
public synchronized StatelessSession getSession() {
	if (sessionFactory == null) {
		try {
			ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
			sessionFactory = configuration.buildSessionFactory(serviceRegistry);
		} catch (HibernateException e) {
			log.warn("(HibernateHelper) Hibernate session factory creation failed", e);
			throw new RuntimeException("(HibernateHelper) Hibernate session factory creation failed", e);
		}
	}
	return sessionFactory.openStatelessSession();
}
 
Example 55
Project: lams   File: LocalSessionFactoryBuilder.java   Source Code and License 5 votes vote down vote up
@Override
public Settings buildSettings(Properties props, ServiceRegistry serviceRegistry) throws HibernateException {
	Settings settings = super.buildSettings(props, serviceRegistry);
	if (this.cacheRegionFactory != null) {
		try {
			Method setRegionFactory = Settings.class.getDeclaredMethod("setRegionFactory", RegionFactory.class);
			setRegionFactory.setAccessible(true);
			setRegionFactory.invoke(settings, this.cacheRegionFactory);
		}
		catch (Exception ex) {
			throw new IllegalStateException("Failed to invoke Hibernate's setRegionFactory method", ex);
		}
	}
	return settings;
}
 
Example 56
Project: lams   File: SettingsFactory.java   Source Code and License 5 votes vote down vote up
protected QueryCacheFactory createQueryCacheFactory(Properties properties, ServiceRegistry serviceRegistry) {
	String queryCacheFactoryClassName = ConfigurationHelper.getString(
			AvailableSettings.QUERY_CACHE_FACTORY, properties, StandardQueryCacheFactory.class.getName()
	);
	LOG.debugf( "Query cache factory: %s", queryCacheFactoryClassName );
	try {
		return (QueryCacheFactory) serviceRegistry.getService( ClassLoaderService.class )
				.classForName( queryCacheFactoryClassName )
				.newInstance();
	}
	catch (Exception e) {
		throw new HibernateException( "could not instantiate QueryCacheFactory: " + queryCacheFactoryClassName, e );
	}
}
 
Example 57
Project: lams   File: SettingsFactory.java   Source Code and License 5 votes vote down vote up
protected QueryTranslatorFactory createQueryTranslatorFactory(Properties properties, ServiceRegistry serviceRegistry) {
	String className = ConfigurationHelper.getString(
			AvailableSettings.QUERY_TRANSLATOR, properties, "org.hibernate.hql.internal.ast.ASTQueryTranslatorFactory"
	);
	LOG.debugf( "Query translator: %s", className );
	try {
		return (QueryTranslatorFactory) serviceRegistry.getService( ClassLoaderService.class )
				.classForName( className )
				.newInstance();
	}
	catch ( Exception e ) {
		throw new HibernateException( "could not instantiate QueryTranslatorFactory: " + className, e );
	}
}
 
Example 58
Project: lams   File: Helper.java   Source Code and License 5 votes vote down vote up
public static Class classForName(String className, ServiceRegistry serviceRegistry) {
	ClassLoaderService classLoaderService = serviceRegistry.getService( ClassLoaderService.class );
	try {
		return classLoaderService.classForName( className );
	}
	catch ( ClassLoadingException e ) {
		throw new MappingException( "Could not find class: " + className );
	}
}
 
Example 59
Project: lams   File: IndexBuilder.java   Source Code and License 5 votes vote down vote up
IndexBuilder(Index index, ServiceRegistry serviceRegistry) {
	this.index = index;
	this.serviceRegistry = serviceRegistry;
	this.annotations = new HashMap<DotName, List<AnnotationInstance>>();
	this.subclasses = new HashMap<DotName, List<ClassInfo>>();
	this.implementors = new HashMap<DotName, List<ClassInfo>>();
	this.classes = new HashMap<DotName, ClassInfo>();
	this.classInfoAnnotationsMap = new HashMap<DotName, Map<DotName, List<AnnotationInstance>>>();
	this.indexedClassInfoAnnotationsMap = new HashMap<DotName, Map<DotName, List<AnnotationInstance>>>();
}
 
Example 60
Project: lams   File: MockHelper.java   Source Code and License 5 votes vote down vote up
static void classArrayValue(String name, List<String> classNameList, List<AnnotationValue> list, ServiceRegistry serviceRegistry) {
	if ( isNotEmpty( classNameList ) ) {

		List<AnnotationValue> clazzValueList = new ArrayList<AnnotationValue>( classNameList.size() );
		for ( String clazz : classNameList ) {
			addToCollectionIfNotNull( clazzValueList, classValue( "", clazz, serviceRegistry ) );
		}

		list.add(
				AnnotationValue.createArrayValue(
						name, toArray( clazzValueList )
				)
		);
	}
}