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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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();

}