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

The following examples show how to use org.hibernate.boot.registry.StandardServiceRegistry. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
/**
 * Build the StandardServiceRegistry.
 *
 * @return The StandardServiceRegistry.
 */
@SuppressWarnings("unchecked")
public StandardServiceRegistry build() {
    applyServiceContributingIntegrators();
    applyServiceContributors();

    @SuppressWarnings("rawtypes")
    final Map settingsCopy = new HashMap( settings );
    settingsCopy.put( org.hibernate.boot.cfgxml.spi.CfgXmlAccessService.LOADED_CONFIG_KEY, aggregatedCfgXml );
    ConfigurationHelper.resolvePlaceHolders( settingsCopy );

    return new StandardServiceRegistryImpl(
            autoCloseRegistry,
            bootstrapServiceRegistry,
            initiators,
            providedServices,
            settingsCopy
    );
}
 
Example 2
private void mysqlConfiguration(StandardServiceRegistry registry) {
	registry.getService( ConnectionProvider.class ); //force the NoJdbcConnectionProvider to load first
	registry.getService( SchemaManagementTool.class )
			.setCustomDatabaseGenerationTarget( new ReactiveGenerationTarget(registry) {
				@Override
				public void prepare() {
					super.prepare();
					if ( dbType() == DBType.MYSQL ) {
						accept("set foreign_key_checks = 0");
					}
				}
				@Override
				public void release() {
					if ( dbType() == DBType.MYSQL ) {
						accept("set foreign_key_checks = 1");
					}
					super.release();
				}
			} );
}
 
Example 3
/**
 * The main method that does the CRUD operations.
 */
public static void main(String[] args) {
  // create a Hibernate sessionFactory and session
  StandardServiceRegistry registry = new StandardServiceRegistryBuilder().configure().build();
  SessionFactory sessionFactory = new MetadataSources(registry).buildMetadata()
      .buildSessionFactory();
  Session session = sessionFactory.openSession();

  clearData(session);

  writeData(session);

  readData(session);

  // close Hibernate session and sessionFactory
  session.close();
  sessionFactory.close();
}
 
Example 4
Source Project: tutorials   Source File: NamedParameterUnitTest.java    License: MIT License 6 votes vote down vote up
@Before
public void setUp() throws Exception {
    final StandardServiceRegistry registry = new StandardServiceRegistryBuilder()
            .configure()
            .build();
    try {
        sessionFactory = new MetadataSources(registry).buildMetadata().buildSessionFactory();
        Session session = sessionFactory.openSession();
        session.beginTransaction();
        session.save(new Event("Event 1"));
        session.save(new Event("Event 2"));
        session.getTransaction().commit();
        session.close();
    } catch (Exception e) {
        fail(e);
        StandardServiceRegistryBuilder.destroy(registry);
    }
}
 
Example 5
Source Project: quarkus   Source File: FastBootMetadataBuilder.java    License: Apache License 2.0 6 votes vote down vote up
private void registerIdentifierGenerators(StandardServiceRegistry ssr) {
    final StrategySelector strategySelector = ssr.getService(StrategySelector.class);

    // apply id generators
    final Object idGeneratorStrategyProviderSetting = buildTimeSettings
            .get(AvailableSettings.IDENTIFIER_GENERATOR_STRATEGY_PROVIDER);
    if (idGeneratorStrategyProviderSetting != null) {
        final IdentifierGeneratorStrategyProvider idGeneratorStrategyProvider = strategySelector
                .resolveStrategy(IdentifierGeneratorStrategyProvider.class, idGeneratorStrategyProviderSetting);
        final MutableIdentifierGeneratorFactory identifierGeneratorFactory = ssr
                .getService(MutableIdentifierGeneratorFactory.class);
        if (identifierGeneratorFactory == null) {
            throw persistenceException("Application requested custom identifier generator strategies, "
                    + "but the MutableIdentifierGeneratorFactory could not be found");
        }
        for (Map.Entry<String, Class<?>> entry : idGeneratorStrategyProvider.getStrategies().entrySet()) {
            identifierGeneratorFactory.register(entry.getKey(), entry.getValue());
        }
    }
}
 
Example 6
Source Project: quarkus   Source File: FastBootMetadataBuilder.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Greatly simplified copy of
 * org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl#populate(org.hibernate.boot.MetadataBuilder,
 * org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.MergedSettings,
 * org.hibernate.boot.registry.StandardServiceRegistry, java.util.List)
 */
protected void populate(MetadataBuilder metamodelBuilder, List<CacheRegionDefinition> cacheRegionDefinitions,
        StandardServiceRegistry ssr) {

    ((MetadataBuilderImplementor) metamodelBuilder).getBootstrapContext().markAsJpaBootstrap();

    metamodelBuilder.applyScanEnvironment(new StandardJpaScanEnvironmentImpl(persistenceUnit));
    metamodelBuilder.applyScanOptions(new StandardScanOptions(
            (String) buildTimeSettings.get(org.hibernate.cfg.AvailableSettings.SCANNER_DISCOVERY),
            persistenceUnit.isExcludeUnlistedClasses()));

    if (cacheRegionDefinitions != null) {
        cacheRegionDefinitions.forEach(metamodelBuilder::applyCacheRegionDefinition);
    }

    final TypeContributorList typeContributorList = (TypeContributorList) buildTimeSettings
            .get(EntityManagerFactoryBuilderImpl.TYPE_CONTRIBUTORS);
    if (typeContributorList != null) {
        typeContributorList.getTypeContributors().forEach(metamodelBuilder::applyTypes);
    }
}
 
Example 7
Source Project: tutorials   Source File: HibernateLoggingIntegrationTest.java    License: MIT License 6 votes vote down vote up
@Before
public void setUp() throws IOException {
    final StandardServiceRegistry registry = new StandardServiceRegistryBuilder().configure("hibernate-logging.cfg.xml")
        .build();
    try {
        sessionFactory = new MetadataSources(registry).buildMetadata()
            .buildSessionFactory();
        Session session = sessionFactory.openSession();
        session.beginTransaction();
        session.save(new Employee("John Smith", "001"));
        session.getTransaction()
            .commit();
        session.close();
    } catch (Exception e) {
        fail(e);
        StandardServiceRegistryBuilder.destroy(registry);
    }
}
 
Example 8
private StandardServiceRegistry rewireMetadataAndExtractServiceRegistry(RuntimeSettings runtimeSettings,
        RecordedState rs) {
    PreconfiguredServiceRegistryBuilder serviceRegistryBuilder = new PreconfiguredServiceRegistryBuilder(rs);

    runtimeSettings.getSettings().forEach((key, value) -> {
        serviceRegistryBuilder.applySetting(key, value);
    });

    for (ProvidedService<?> providedService : rs.getProvidedServices()) {
        serviceRegistryBuilder.addService(providedService);
    }

    // TODO serviceRegistryBuilder.addInitiator( )

    StandardServiceRegistryImpl standardServiceRegistry = serviceRegistryBuilder.buildNewServiceRegistry();
    return standardServiceRegistry;
}
 
Example 9
Source Project: tutorials   Source File: HibernateUtil.java    License: MIT License 6 votes vote down vote up
/**
 * Generates database create commands for the specified entities using Hibernate native API, SchemaExport.
 * Creation commands are exported into the create.sql file.
 */
public static void generateSchema() {
    Map<String, String> settings = new HashMap<>();
    settings.put(Environment.URL, "jdbc:h2:mem:schema");

    StandardServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(settings).build();

    MetadataSources metadataSources = new MetadataSources(serviceRegistry);
    metadataSources.addAnnotatedClass(Account.class);
    metadataSources.addAnnotatedClass(AccountSetting.class);
    Metadata metadata = metadataSources.buildMetadata();

    SchemaExport schemaExport = new SchemaExport();
    schemaExport.setFormat(true);
    schemaExport.setOutputFile("create.sql");
    schemaExport.createOnly(EnumSet.of(TargetType.SCRIPT), metadata);
}
 
Example 10
Source Project: teiid-spring-boot   Source File: SchemaBuilderUtility.java    License: Apache License 2.0 6 votes vote down vote up
public static ArtifactCollector generateHibernateModel(MetadataFactory source,
        StandardServiceRegistry serviceRegistry) {
    ReverseEngineeringStrategy strategy = new DefaultReverseEngineeringStrategy();
    MetadataBuildingOptions options = new MetadataBuildingOptionsImpl(serviceRegistry);

    BootstrapContext bootstrapContext = new BootstrapContextImpl(serviceRegistry, options);

    InFlightMetadataCollectorImpl metadataCollector = new InFlightMetadataCollectorImpl(bootstrapContext, options);
    MetadataBuildingContext buildingContext = new MetadataBuildingContextRootImpl(bootstrapContext, options,
            metadataCollector);

    TeiidJDBCBinder binder = new TeiidJDBCBinder(serviceRegistry, new Properties(), buildingContext, strategy,
            false, metadataCollector, source);
    Metadata metadata = metadataCollector.buildMetadataInstance(buildingContext);
    binder.readFromDatabase(null, null, buildMapping(metadata));

    HibernateMappingExporter exporter = new HibernateMappingExporter() {
        @Override
        public Metadata getMetadata() {
            return metadata;
        }
    };
    exporter.setOutputDirectory(TMP_DIR);
    exporter.start();
    return exporter.getArtifactCollector();
}
 
Example 11
Source Project: teiid-spring-boot   Source File: TeiidServer.java    License: Apache License 2.0 6 votes vote down vote up
private Metadata getMetadata(Set<BeanDefinition> components, PhysicalNamingStrategy namingStrategy,
        MetadataFactory mf) {
    ServiceRegistry registry = metadataSources.getServiceRegistry();
    StandardServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder(
            (BootstrapServiceRegistry) registry).applySetting(AvailableSettings.DIALECT, TeiidDialect.class)
            .build();
    // Generate Hibernate model based on @Entity definitions
    for (BeanDefinition c : components) {
        try {
            Class<?> clazz = Class.forName(c.getBeanClassName());
            metadataSources.addAnnotatedClass(clazz);
        } catch (ClassNotFoundException e) {
        }
    }
    return metadataSources.getMetadataBuilder(serviceRegistry).applyPhysicalNamingStrategy(namingStrategy).build();
}
 
Example 12
Source Project: lams   Source File: SchemaExport.java    License: GNU General Public License v2.0 6 votes vote down vote up
public static void execute(CommandLineArgs commandLineArgs) throws Exception {
	StandardServiceRegistry serviceRegistry = buildStandardServiceRegistry( commandLineArgs );
	try {
		final MetadataImplementor metadata = buildMetadata( commandLineArgs, serviceRegistry );

		new SchemaExport()
				.setHaltOnError( commandLineArgs.halt )
				.setOutputFile( commandLineArgs.outputFile )
				.setDelimiter( commandLineArgs.delimiter )
				.setFormat( commandLineArgs.format )
				.setManageNamespaces( commandLineArgs.manageNamespaces )
				.setImportFiles( commandLineArgs.importFile )
				.execute( commandLineArgs.targetTypes, commandLineArgs.action, metadata, serviceRegistry );
	}
	finally {
		StandardServiceRegistryBuilder.destroy( serviceRegistry );
	}
}
 
Example 13
Source Project: lams   Source File: SchemaExport.java    License: GNU General Public License v2.0 6 votes vote down vote up
private static StandardServiceRegistry buildStandardServiceRegistry(CommandLineArgs commandLineArgs)
		throws Exception {
	final BootstrapServiceRegistry bsr = new BootstrapServiceRegistryBuilder().build();
	final StandardServiceRegistryBuilder ssrBuilder = new StandardServiceRegistryBuilder( bsr );

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

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

	return ssrBuilder.build();
}
 
Example 14
Source Project: lams   Source File: SchemaUpdate.java    License: GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) {
	try {
		final CommandLineArgs parsedArgs = CommandLineArgs.parseCommandLineArgs( args );
		final StandardServiceRegistry serviceRegistry = buildStandardServiceRegistry( parsedArgs );

		try {
			final MetadataImplementor metadata = buildMetadata( parsedArgs, serviceRegistry );

			new SchemaUpdate()
					.setOutputFile( parsedArgs.outputFile )
					.setDelimiter( parsedArgs.delimiter )
					.execute( parsedArgs.targetTypes, metadata, serviceRegistry );
		}
		finally {
			StandardServiceRegistryBuilder.destroy( serviceRegistry );
		}
	}
	catch (Exception e) {
		LOG.unableToRunSchemaUpdate( e );
	}
}
 
Example 15
Source Project: lams   Source File: SchemaUpdate.java    License: GNU General Public License v2.0 6 votes vote down vote up
private static StandardServiceRegistry buildStandardServiceRegistry(CommandLineArgs parsedArgs) throws Exception {
	final BootstrapServiceRegistry bsr = new BootstrapServiceRegistryBuilder().build();
	final StandardServiceRegistryBuilder ssrBuilder = new StandardServiceRegistryBuilder( bsr );

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

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

	return ssrBuilder.build();
}
 
Example 16
Source Project: lams   Source File: SchemaValidator.java    License: GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) {
	try {
		final CommandLineArgs parsedArgs = CommandLineArgs.parseCommandLineArgs( args );
		final StandardServiceRegistry serviceRegistry = buildStandardServiceRegistry( parsedArgs );

		try {
			final MetadataImplementor metadata = buildMetadata( parsedArgs, serviceRegistry );
			new SchemaValidator().validate( metadata, serviceRegistry );
		}
		finally {
			StandardServiceRegistryBuilder.destroy( serviceRegistry );
		}
	}
	catch (Exception e) {
		LOG.unableToRunSchemaUpdate( e );
	}
}
 
Example 17
Source Project: lams   Source File: SchemaValidator.java    License: GNU General Public License v2.0 6 votes vote down vote up
private static StandardServiceRegistry buildStandardServiceRegistry(CommandLineArgs parsedArgs) throws Exception {
	final BootstrapServiceRegistry bsr = new BootstrapServiceRegistryBuilder().build();
	final StandardServiceRegistryBuilder ssrBuilder = new StandardServiceRegistryBuilder( bsr );

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

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

	return ssrBuilder.build();
}
 
Example 18
Source Project: cosmo   Source File: DbInitializer.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Schema validation
 */
// TODO
private void validateSchema() {
    try {
        SessionFactory factory = this.localSessionFactory.unwrap(SessionFactory.class);
        StandardServiceRegistry registry = factory.getSessionFactoryOptions().getServiceRegistry();
        MetadataSources sources = new MetadataSources(registry);
        sources.addPackage("org.unitedinternet.cosmo.model.hibernate");
        Metadata metadata = sources.buildMetadata(registry);
        new SchemaValidator().validate(metadata);
        LOG.info("Schema validation passed");
    } catch (HibernateException e) {
        LOG.error("error validating schema", e);
        throw e;
    }
}
 
Example 19
Source Project: juddi   Source File: App.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Method that actually creates the file.
 *
 * @param dbDialect to use
 */
private void generate(Dialect dialect) {

        StandardServiceRegistryBuilder ssrb = new StandardServiceRegistryBuilder();
        ssrb.applySetting("hibernate.dialect", dialect.getDialectClass());
        StandardServiceRegistry standardServiceRegistry = ssrb.build();

        MetadataSources metadataSources = new MetadataSources(standardServiceRegistry);
        for (Class clzz : jpaClasses) {
                metadataSources.addAnnotatedClass(clzz);
        }

        Metadata metadata = metadataSources.buildMetadata();

        SchemaExport export = new SchemaExport();

        export.setDelimiter(";");
        export.setOutputFile(dialect.name().toLowerCase() + ".ddl");
        //export.execute(true, false, false, true);
        export.execute(EnumSet.of(TargetType.SCRIPT), Action.BOTH, metadata);
}
 
Example 20
Source Project: lams   Source File: MetadataBuilderImpl.java    License: GNU General Public License v2.0 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 21
@Override
protected void initialize(MetadataBuildingOptions buildingOptions, SessionFactoryOptions sessionFactoryOptions) {
	final StandardServiceRegistry serviceRegistry = buildingOptions.getServiceRegistry();
	final JdbcEnvironment jdbcEnvironment = serviceRegistry.getService( JdbcEnvironment.class );
	final ConfigurationService configService = serviceRegistry.getService( ConfigurationService.class );

	final String catalogName = configService.getSetting(
			CATALOG,
			StandardConverters.STRING,
			configService.getSetting( AvailableSettings.DEFAULT_CATALOG, StandardConverters.STRING )
	);
	final String schemaName = configService.getSetting(
			SCHEMA,
			StandardConverters.STRING,
			configService.getSetting( AvailableSettings.DEFAULT_SCHEMA, StandardConverters.STRING )
	);

	this.catalog = jdbcEnvironment.getIdentifierHelper().toIdentifier( catalogName );
	this.schema = jdbcEnvironment.getIdentifierHelper().toIdentifier( schemaName );

	this.dropIdTables = configService.getSetting(
			DROP_ID_TABLES,
			StandardConverters.BOOLEAN,
			false
	);
}
 
Example 22
@Test
public void testGridNameOverrideConfigBuilder() {
	IgniteConfiguration config = createConfig( CUSTOM_GRID_NAME );
	try ( Ignite ignite = Ignition.start( config ) ) {

		StandardServiceRegistry registry = registryBuilder()
				.applySetting( IgniteProperties.CONFIGURATION_CLASS_NAME, MyTinyGridConfigBuilder.class.getName() )
				.applySetting( IgniteProperties.IGNITE_INSTANCE_NAME, CUSTOM_GRID_NAME )
				.build();

		try ( OgmSessionFactory sessionFactory = createFactory( registry ) ) {
			assertThat( Ignition.allGrids() ).hasSize( 1 );
			assertThat( Ignition.allGrids().get( 0 ).name() ).isEqualTo( CUSTOM_GRID_NAME );
		}
	}
}
 
Example 23
public HibernateDatabase(Properties properties) throws HibernateException {

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

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

    }
 
Example 24
/**
 * Main method that runs a simple console application that saves a {@link Person} entity and then
 * retrieves it to print to the console.
 */
public static void main(String[] args) {

  // Create Hibernate environment objects.
  StandardServiceRegistry registry = new StandardServiceRegistryBuilder()
      .configure()
      .build();
  SessionFactory sessionFactory = new MetadataSources(registry).buildMetadata()
      .buildSessionFactory();
  Session session = sessionFactory.openSession();

  // Save an entity into Spanner Table.
  savePerson(session);

  session.close();
}
 
Example 25
@Override
public EntityManagerFactory build() {
    final MetadataImpl metadata = (MetadataImpl) metadata();
    final StandardServiceRegistry standardServiceRegistry = getStandardServiceRegistry();
    final SessionFactoryBuilderImpl defaultBuilder = new SessionFactoryBuilderImpl( metadata, metadata.getBootstrapContext() );
    final SessionFactoryBuilderImplementor reactiveSessionFactoryBuilder = new ReactiveSessionFactoryBuilder( metadata, defaultBuilder );
    populateSfBuilder( reactiveSessionFactoryBuilder, standardServiceRegistry );

    try {
        return reactiveSessionFactoryBuilder.build();
    }
    catch (Exception e) {
        throw persistenceException( "Unable to build Hibernate SessionFactory", e );
    }
}
 
Example 26
@Test
public void createReactiveSessionFactory() {
	StandardServiceRegistry registry = new ReactiveServiceRegistryBuilder()
			.applySetting( Settings.TRANSACTION_COORDINATOR_STRATEGY, "jta" )
			.applySetting( Settings.DIALECT, PostgreSQL9Dialect.class.getName() )
			.build();

	Stage.SessionFactory factory = new MetadataSources( registry )
			.buildMetadata()
			.getSessionFactoryBuilder()
			.build()
			.unwrap( Stage.SessionFactory.class );

	assertThat( factory ).isNotNull();
}
 
Example 27
@Before
public void before() {
	Configuration configuration = constructConfiguration();
	StandardServiceRegistry registry = new ReactiveServiceRegistryBuilder()
			.applySettings( configuration.getProperties() )
			.build();
	mysqlConfiguration( registry );
	sessionFactory = configuration.buildSessionFactory( registry );
	poolProvider = registry.getService( ReactiveConnectionPool.class );
}
 
Example 28
@Before
public void before() {
	StandardServiceRegistry registry = new ReactiveServiceRegistryBuilder()
			.applySettings( constructConfiguration().getProperties() )
			.build();

	sessionFactory = constructConfiguration().buildSessionFactory( registry );
	poolProvider = registry.getService( ReactiveConnectionPool.class );
}
 
Example 29
@Test
public void testUserAgentContribution() throws SQLException {
  // create mock Driver so we can intercept the call to Driver.connect(url, props)
  Driver mockDriver = mock(Driver.class);
  when(mockDriver.connect(any(), any())).thenReturn(mock(Connection.class));

  // make sure our mock driver is discovered by Hibernate
  deregisterDrivers();
  DriverManager.registerDriver(mockDriver);

  StandardServiceRegistry registry = new StandardServiceRegistryBuilder()
      .applySetting("hibernate.dialect", SpannerDialect.class.getName())
      // must NOT set a driver class name so that Hibernate will use java.sql.DriverManager
      // and discover the only mock driver we have set up.
      .applySetting("hibernate.connection.url", "unused")
      .applySetting("hibernate.connection.username", "unused")
      .applySetting("hibernate.connection.password", "unused")
      .build();

  // trigger creation of connections for the connection pool
  Metadata metadata = new MetadataSources(registry).buildMetadata();

  // verify that our mock Driver.connect(url, props) was called and capture the properties
  ArgumentCaptor<Properties> propertiesArgumentCaptor = ArgumentCaptor.forClass(Properties.class);
  verify(mockDriver, atLeastOnce())
      .connect(any(String.class), propertiesArgumentCaptor.capture());

  // verify the the userAgent was passed in with properties
  assertThat(propertiesArgumentCaptor.getValue().getProperty("userAgent")).isEqualTo("sp-hib");
}
 
Example 30
/**
 * Main method that runs a simple console application that saves a {@link Person} entity and then
 * retrieves it to print to the console.
 */
public static void main(String[] args) {

  // Create Hibernate environment objects.
  StandardServiceRegistry registry = new StandardServiceRegistryBuilder()
      .configure()
      .build();
  SessionFactory sessionFactory = new MetadataSources(registry).buildMetadata()
      .buildSessionFactory();
  Session session = sessionFactory.openSession();

  // Save an entity into Spanner Table.
  savePerson(session);
}