org.hibernate.cfg.AvailableSettings Java Examples

The following examples show how to use org.hibernate.cfg.AvailableSettings. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: AbstractTest.java    From high-performance-java-persistence with Apache License 2.0 6 votes vote down vote up
protected EntityManagerFactory newEntityManagerFactory() {
    PersistenceUnitInfo persistenceUnitInfo = persistenceUnitInfo(getClass().getSimpleName());
    Map configuration = properties();
    Interceptor interceptor = interceptor();
    if (interceptor != null) {
        configuration.put(AvailableSettings.INTERCEPTOR, interceptor);
    }
    Integrator integrator = integrator();
    if (integrator != null) {
        configuration.put("hibernate.integrator_provider", (IntegratorProvider) () -> Collections.singletonList(integrator));
    }

    EntityManagerFactoryBuilderImpl entityManagerFactoryBuilder = new EntityManagerFactoryBuilderImpl(
        new PersistenceUnitInfoDescriptor(persistenceUnitInfo), configuration
    );
    return entityManagerFactoryBuilder.build();
}
 
Example #2
Source File: ItemDaoImpl.java    From cosmo with Apache License 2.0 6 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public <STAMP_TYPE extends Stamp> STAMP_TYPE findStampByInternalItemUid(String internalItemUid,
        Class<STAMP_TYPE> clazz) {

    List<Stamp> stamps = (List<Stamp>) em.createNamedQuery("item.stamps.by.uid")
            .setParameter("uid", internalItemUid).setHint(AvailableSettings.JPA_SHARED_CACHE_STORE_MODE, null)
            .setHint(AvailableSettings.JPA_SHARED_CACHE_RETRIEVE_MODE, null).getResultList();
    for (Stamp stamp : stamps) {
        if (clazz.isInstance(stamp)) {
            return clazz.cast(stamp);
        }
    }

    return null;
}
 
Example #3
Source File: JtaPlatformInitiator.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
@SuppressWarnings( {"unchecked"})
public JtaPlatform initiateService(Map configurationValues, ServiceRegistryImplementor registry) {
	final Object setting = configurationValues.get( AvailableSettings.JTA_PLATFORM );
	JtaPlatform platform = registry.getService( StrategySelector.class ).resolveStrategy( JtaPlatform.class, setting );

	if ( platform == null ) {
		LOG.debugf( "No JtaPlatform was specified, checking resolver" );
		platform = registry.getService( JtaPlatformResolver.class ).resolveJtaPlatform( configurationValues, registry );
	}

	if ( platform == null ) {
		LOG.debugf( "No JtaPlatform was specified, checking resolver" );
		platform = getFallbackProvider( configurationValues, registry );
	}

	return platform;
}
 
Example #4
Source File: OptimizerFactory.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Determine the optimizer to use when there was not one explicitly specified.
 */
public static String determineImplicitOptimizerName(int incrementSize, Properties configSettings) {
	if ( incrementSize <= 1 ) {
		return StandardOptimizerDescriptor.NONE.getExternalName();
	}

	// see if the user defined a preferred pooled optimizer...
	final String preferredPooledOptimizerStrategy = configSettings.getProperty( AvailableSettings.PREFERRED_POOLED_OPTIMIZER );
	if ( StringHelper.isNotEmpty( preferredPooledOptimizerStrategy ) ) {
		return preferredPooledOptimizerStrategy;
	}

	// otherwise fallback to the fallback strategy (considering the deprecated PREFER_POOLED_VALUES_LO setting)
	return ConfigurationHelper.getBoolean( AvailableSettings.PREFER_POOLED_VALUES_LO, configSettings, false )
			? StandardOptimizerDescriptor.POOLED_LO.getExternalName()
			: StandardOptimizerDescriptor.POOLED.getExternalName();
}
 
Example #5
Source File: HibernateExceptionUnitTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
public void whenWrongDialectSpecified_thenCommandAcceptanceException() {
    thrown.expect(SchemaManagementException.class);
    thrown.expectCause(isA(CommandAcceptanceException.class));
    thrown.expectMessage("Halting on error : Error executing DDL");

    Configuration cfg = getConfiguration();
    cfg.setProperty(AvailableSettings.DIALECT,
        "org.hibernate.dialect.MySQLDialect");
    cfg.setProperty(AvailableSettings.HBM2DDL_AUTO, "update");

    // This does not work due to hibernate bug
    // cfg.setProperty(AvailableSettings.HBM2DDL_HALT_ON_ERROR,"true");
    cfg.getProperties()
        .put(AvailableSettings.HBM2DDL_HALT_ON_ERROR, true);

    cfg.addAnnotatedClass(Product.class);
    cfg.buildSessionFactory();
}
 
Example #6
Source File: ConfigBean.java    From sailfish-core with Apache License 2.0 6 votes vote down vote up
public boolean equals(Configuration configuration) {

			Properties prop = configuration.getProperties();

			if (!driverClass.equals(prop.getProperty(AvailableSettings.DRIVER))) {
				return false;
			}
			if (!dialect.equals(prop.getProperty(AvailableSettings.DIALECT))) {
				return false;
			}
			if (!preferredTestQuery.equals(prop.getProperty(PREFFERED_TEST_QUERY))) {
				return false;
			}
			if (!userName.equals(prop.getProperty(AvailableSettings.USER))) {
				return false;
			}
			if (!password.equals(prop.getProperty(AvailableSettings.PASS))) {
				return false;
			}
			if (!createProtocolUrl(this).equals(prop.getProperty(AvailableSettings.URL))) {
				return false;
			}

			return true;
		}
 
Example #7
Source File: FastBootMetadataBuilder.java    From quarkus with 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 #8
Source File: FastBootHibernateReactivePersistenceProvider.java    From quarkus with Apache License 2.0 6 votes vote down vote up
private void registerVertxPool(String persistenceUnitName,
        RuntimeSettings runtimeSettings,
        PreconfiguredReactiveServiceRegistryBuilder serviceRegistry) {
    if (runtimeSettings.isConfigured(AvailableSettings.URL)) {
        // the pool has been defined in the persistence unit, we can bail out
        return;
    }

    // for now we only support one pool but this will change
    InstanceHandle<Pool> poolHandle = Arc.container().instance(Pool.class);
    if (!poolHandle.isAvailable()) {
        throw new IllegalStateException("No pool has been defined for persistence unit " + persistenceUnitName);
    }

    serviceRegistry.addInitiator(new QuarkusReactiveConnectionPoolInitiator(poolHandle.get()));
}
 
Example #9
Source File: LocalSessionFactoryBuilder.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Build the {@code SessionFactory}.
 */
@Override
@SuppressWarnings("deprecation")
public SessionFactory buildSessionFactory() throws HibernateException {
	ClassLoader appClassLoader = (ClassLoader) getProperties().get(AvailableSettings.APP_CLASSLOADER);
	Thread currentThread = Thread.currentThread();
	ClassLoader threadContextClassLoader = currentThread.getContextClassLoader();
	boolean overrideClassLoader =
			(appClassLoader != null && !appClassLoader.equals(threadContextClassLoader));
	if (overrideClassLoader) {
		currentThread.setContextClassLoader(appClassLoader);
	}
	try {
		return super.buildSessionFactory();
	}
	finally {
		if (overrideClassLoader) {
			currentThread.setContextClassLoader(threadContextClassLoader);
		}
	}
}
 
Example #10
Source File: NamedProcedureCallDefinition.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
static ParameterDefinition from(
		ParameterStrategy parameterStrategy,
		StoredProcedureParameter parameterAnnotation,
		int adjustedPosition,
		Map<String, Object> queryHintMap) {
	// see if there was an explicit hint for this parameter in regards to NULL passing
	final Object explicitNullPassingHint;
	if ( parameterStrategy == ParameterStrategy.NAMED ) {
		explicitNullPassingHint = queryHintMap.get( AvailableSettings.PROCEDURE_NULL_PARAM_PASSING + '.' + parameterAnnotation.name() );
	}
	else {
		explicitNullPassingHint = queryHintMap.get( AvailableSettings.PROCEDURE_NULL_PARAM_PASSING + '.' + adjustedPosition );
	}

	return new ParameterDefinition(
			adjustedPosition,
			parameterAnnotation,
			interpretBoolean( explicitNullPassingHint )
	);
}
 
Example #11
Source File: TransactionCoordinatorBuilderInitiator.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
private static Object determineStrategySelection(Map configurationValues) {
	final Object coordinatorStrategy = configurationValues.get( AvailableSettings.TRANSACTION_COORDINATOR_STRATEGY );
	if ( coordinatorStrategy != null ) {
		return coordinatorStrategy;
	}

	final Object legacySetting = configurationValues.get( LEGACY_SETTING_NAME );
	if ( legacySetting != null ) {
		DeprecationLogger.DEPRECATION_LOGGER.logDeprecatedTransactionFactorySetting(
				LEGACY_SETTING_NAME,
				AvailableSettings.TRANSACTION_COORDINATOR_STRATEGY
		);
		return legacySetting;
	}

	// triggers the default
	return null;
}
 
Example #12
Source File: HibernateUtil.java    From FrameworkBenchmarks with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private static SessionFactory createSessionFactory() {
    try {
        Configuration configuration = configuration();
        configuration.setProperty(AvailableSettings.DIALECT, MySQLDialect.class.getName());
        configuration.setProperty(AvailableSettings.USE_QUERY_CACHE, "false");
        configuration.setProperty(AvailableSettings.SHOW_SQL, "false");
        configuration.setProperty(AvailableSettings.CURRENT_SESSION_CONTEXT_CLASS, "thread");
        configuration.setProperty("hibernate.hikari.maximumPoolSize", String.valueOf(Runtime.getRuntime().availableProcessors() * 2));
        configuration.addAnnotatedClass(World.class);
        configuration.addAnnotatedClass(Fortune.class);
        StandardServiceRegistryBuilder serviceRegistryBuilder = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties());
        return configuration.buildSessionFactory(serviceRegistryBuilder.build());
    } catch (RuntimeException ex) {
        LOGGER.error("Failed to create session factory");
        throw ex;
    }
}
 
Example #13
Source File: LockModePessimisticReadWriteIntegrationTest.java    From high-performance-java-persistence with Apache License 2.0 6 votes vote down vote up
@Test
public void testPessimisticNoWait() {
    LOGGER.info("Test PESSIMISTIC_READ blocks PESSIMISTIC_WRITE, NO WAIT fails fast");

    doInJPA(entityManager -> {
        Post post = entityManager.find(Post.class, 1L,
            LockModeType.PESSIMISTIC_WRITE
        );

        executeSync(() -> doInJPA(_entityManager -> {
            try {
                Post _post = _entityManager.find(Post.class, 1L,
                    LockModeType.PESSIMISTIC_WRITE,
                    Collections.singletonMap(
                        AvailableSettings.JPA_LOCK_TIMEOUT, LockOptions.NO_WAIT
                    )
                );
                fail("Should throw PessimisticEntityLockException");
            } catch (LockTimeoutException expected) {
                //This is expected since the first transaction already acquired this lock
            }
        }));
    });
}
 
Example #14
Source File: DriverManagerConnectionProviderImpl.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
private PooledConnections buildPool(Map configurationValues) {
	final boolean autoCommit = ConfigurationHelper.getBoolean(
			AvailableSettings.AUTOCOMMIT,
			configurationValues,
			false
	);
	final int minSize = ConfigurationHelper.getInt( MIN_SIZE, configurationValues, 1 );
	final int maxSize = ConfigurationHelper.getInt( AvailableSettings.POOL_SIZE, configurationValues, 20 );
	final int initialSize = ConfigurationHelper.getInt( INITIAL_SIZE, configurationValues, minSize );

	ConnectionCreator connectionCreator = buildCreator( configurationValues );
	PooledConnections.Builder pooledConnectionBuilder = new PooledConnections.Builder(
			connectionCreator,
			autoCommit
	);
	pooledConnectionBuilder.initialSize( initialSize );
	pooledConnectionBuilder.minSize( minSize );
	pooledConnectionBuilder.maxSize( maxSize );

	return pooledConnectionBuilder.build();
}
 
Example #15
Source File: HibernateTransactionManagerTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void testSetJtaTransactionManager() throws Exception {
	DataSource ds = mock(DataSource.class);
	TransactionManager tm = mock(TransactionManager.class);
	UserTransaction ut = mock(UserTransaction.class);
	TransactionSynchronizationRegistry tsr = mock(TransactionSynchronizationRegistry.class);
	JtaTransactionManager jtm = new JtaTransactionManager();
	jtm.setTransactionManager(tm);
	jtm.setUserTransaction(ut);
	jtm.setTransactionSynchronizationRegistry(tsr);
	LocalSessionFactoryBuilder lsfb = new LocalSessionFactoryBuilder(ds);
	lsfb.setJtaTransactionManager(jtm);
	Object jtaPlatform = lsfb.getProperties().get(AvailableSettings.JTA_PLATFORM);
	assertNotNull(jtaPlatform);
	assertSame(tm, jtaPlatform.getClass().getMethod("retrieveTransactionManager").invoke(jtaPlatform));
	assertSame(ut, jtaPlatform.getClass().getMethod("retrieveUserTransaction").invoke(jtaPlatform));
	assertTrue(lsfb.getProperties().get(AvailableSettings.TRANSACTION_STRATEGY) instanceof CMTTransactionFactory);
}
 
Example #16
Source File: ResourceLocalReleaseAfterStatementConfiguration.java    From high-performance-java-persistence with Apache License 2.0 6 votes vote down vote up
protected Properties additionalProperties() {
    Properties properties = new Properties();
    properties.setProperty("hibernate.dialect", hibernateDialect);
    properties.setProperty("hibernate.hbm2ddl.auto", "create-drop");
    properties.put(
        "hibernate.integrator_provider",
            (IntegratorProvider) () -> Collections.singletonList(
                new ClassImportIntegrator(Arrays.asList(PostDTO.class))
            )
    );
    properties.put(
        AvailableSettings.CONNECTION_HANDLING,
        //PhysicalConnectionHandlingMode.DELAYED_ACQUISITION_AND_RELEASE_AFTER_STATEMENT
        PhysicalConnectionHandlingMode.DELAYED_ACQUISITION_AND_RELEASE_AFTER_TRANSACTION
    );
    return properties;
}
 
Example #17
Source File: Dialect.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
private void resolveLegacyLimitHandlerBehavior(ServiceRegistry serviceRegistry) {
	// HHH-11194
	// Temporary solution to set whether legacy limit handler behavior should be used.
	final ConfigurationService configurationService = serviceRegistry.getService( ConfigurationService.class );
	legacyLimitHandlerBehavior = configurationService.getSetting(
			AvailableSettings.USE_LEGACY_LIMIT_HANDLERS,
			StandardConverters.BOOLEAN,
			false
	);
}
 
Example #18
Source File: SchemaMultitenancyTest.java    From high-performance-java-persistence with Apache License 2.0 5 votes vote down vote up
@Override
protected void additionalProperties(Properties properties) {
    properties.setProperty(AvailableSettings.HBM2DDL_AUTO, "none");
    properties.setProperty(AvailableSettings.MULTI_TENANT, MultiTenancyStrategy.SCHEMA.name());
    properties.setProperty(AvailableSettings.MULTI_TENANT_IDENTIFIER_RESOLVER, TenantContext.TenantIdentifierResolver.class.getName());
    properties.put(AvailableSettings.MULTI_TENANT_CONNECTION_PROVIDER, MultiTenantConnectionProvider.INSTANCE);
}
 
Example #19
Source File: BaseEntityManagerFunctionalTestCase.java    From google-cloud-spanner-hibernate with GNU Lesser General Public License v2.1 5 votes vote down vote up
@SuppressWarnings("unchecked")
protected Map buildSettings() {
  Map settings = getConfig();
  addMappings(settings);

  if (createSchema()) {
    settings.put(org.hibernate.cfg.AvailableSettings.HBM2DDL_AUTO, "update");
  }
  settings.put(org.hibernate.cfg.AvailableSettings.USE_NEW_ID_GENERATOR_MAPPINGS, "true");
  settings.put(org.hibernate.cfg.AvailableSettings.DIALECT, getDialect().getClass().getName());
  return settings;
}
 
Example #20
Source File: SessionFactoryImpl.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
private void logIfEmptyCompositesEnabled(Map<String, Object> props ) {
	final boolean isEmptyCompositesEnabled = ConfigurationHelper.getBoolean(
			AvailableSettings.CREATE_EMPTY_COMPOSITES_ENABLED,
			props,
			false
	);
	if ( isEmptyCompositesEnabled ) {
		// It would be nice to do this logging in ComponentMetamodel, where
		// AvailableSettings.CREATE_EMPTY_COMPOSITES_ENABLED is actually used.
		// Unfortunately that would end up logging a message several times for
		// each embeddable/composite. Doing it here will log the message only
		// once.
		LOG.emptyCompositesEnabled();
	}
}
 
Example #21
Source File: CacheableNaturalIdTest.java    From google-cloud-spanner-hibernate with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
@SuppressWarnings( "unchecked" )
protected void addConfigOptions(Map options) {
	options.put( AvailableSettings.USE_SECOND_LEVEL_CACHE, Boolean.TRUE.toString() );
	options.put( AvailableSettings.CACHE_REGION_FACTORY, "jcache" );
	options.put( AvailableSettings.USE_QUERY_CACHE, Boolean.TRUE.toString() );
	options.put( AvailableSettings.GENERATE_STATISTICS, Boolean.TRUE.toString() );
	options.put( AvailableSettings.CACHE_REGION_PREFIX, "" );
}
 
Example #22
Source File: AbstractJtaPlatform.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
public void configure(Map configValues) {
	cacheTransactionManager = ConfigurationHelper.getBoolean(
			AvailableSettings.JTA_CACHE_TM,
			configValues,
			canCacheTransactionManagerByDefault()
	);
	cacheUserTransaction = ConfigurationHelper.getBoolean(
			AvailableSettings.JTA_CACHE_UT,
			configValues,
			canCacheUserTransactionByDefault()
	);
}
 
Example #23
Source File: Hbm2ddl.java    From wallride with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
	String locationPattern = "classpath:/org/wallride/domain/*";

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

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

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

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

	new SchemaExport()
			.setHaltOnError(true)
			.setDelimiter(";")
			.create(EnumSet.of(TargetType.STDOUT), metadataBuilder.build());
}
 
Example #24
Source File: ValueGenerationDemo.java    From HibernateDemos with The Unlicense 5 votes vote down vote up
public static void main(String[] args) {
	final Configuration configuration = new Configuration();
	configuration.addAnnotatedClass( Project.class );
	
	// necessary for a known bug, to be fixed in 4.2.9.Final
	configuration.setProperty( AvailableSettings.USE_NEW_ID_GENERATOR_MAPPINGS, "true" );
	
	final SessionFactory sessionFactory = configuration.buildSessionFactory(
			new StandardServiceRegistryBuilder().build() );
	Session s = sessionFactory.openSession();
	
	final Project project = new Project();
	
	s.getTransaction().begin();
	s.persist(project);
	s.getTransaction().commit();
	s.clear();
	
	System.out.println(project.toString());
	
	s.getTransaction().begin();
	s.update(project );
	s.getTransaction().commit();
	s.close();
	
	System.out.println(project.toString());
	
	System.exit(0);
}
 
Example #25
Source File: PhysicalNamingStrategyConfiguration.java    From micronaut-data with Apache License 2.0 5 votes vote down vote up
@Override
public JpaConfiguration onCreated(BeanCreatedEvent<JpaConfiguration> event) {
    JpaConfiguration jpaConfiguration = event.getBean();
    jpaConfiguration.getProperties().putIfAbsent(
            AvailableSettings.PHYSICAL_NAMING_STRATEGY, physicalNamingStrategy
    );
    return jpaConfiguration;
}
 
Example #26
Source File: LocalSessionFactoryBuilder.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * Set the Spring {@link JtaTransactionManager} or the JTA {@link TransactionManager}
 * to be used with Hibernate, if any. Allows for using a Spring-managed transaction
 * manager for Hibernate 5's session and cache synchronization, with the
 * "hibernate.transaction.jta.platform" automatically set to it.
 * <p>A passed-in Spring {@link JtaTransactionManager} needs to contain a JTA
 * {@link TransactionManager} reference to be usable here, except for the WebSphere
 * case where we'll automatically set {@code WebSphereExtendedJtaPlatform} accordingly.
 * <p>Note: If this is set, the Hibernate settings should not contain a JTA platform
 * setting to avoid meaningless double configuration.
 */
public LocalSessionFactoryBuilder setJtaTransactionManager(Object jtaTransactionManager) {
	Assert.notNull(jtaTransactionManager, "Transaction manager reference must not be null");
	if (jtaTransactionManager instanceof JtaTransactionManager) {
		boolean webspherePresent = ClassUtils.isPresent("com.ibm.wsspi.uow.UOWManager", getClass().getClassLoader());
		if (webspherePresent) {
			getProperties().put(AvailableSettings.JTA_PLATFORM,
					"org.hibernate.engine.transaction.jta.platform.internal.WebSphereExtendedJtaPlatform");
		}
		else {
			JtaTransactionManager jtaTm = (JtaTransactionManager) jtaTransactionManager;
			if (jtaTm.getTransactionManager() == null) {
				throw new IllegalArgumentException(
						"Can only apply JtaTransactionManager which has a TransactionManager reference set");
			}
			getProperties().put(AvailableSettings.JTA_PLATFORM,
					new ConfigurableJtaPlatform(jtaTm.getTransactionManager(), jtaTm.getUserTransaction(),
							jtaTm.getTransactionSynchronizationRegistry()));
		}
	}
	else if (jtaTransactionManager instanceof TransactionManager) {
		getProperties().put(AvailableSettings.JTA_PLATFORM,
				new ConfigurableJtaPlatform((TransactionManager) jtaTransactionManager, null, null));
	}
	else {
		throw new IllegalArgumentException(
				"Unknown transaction manager type: " + jtaTransactionManager.getClass().getName());
	}
	return this;
}
 
Example #27
Source File: LocalSessionFactoryBuilder.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * Create a new LocalSessionFactoryBuilder for the given DataSource.
 * @param dataSource the JDBC DataSource that the resulting Hibernate SessionFactory should be using
 * (may be {@code null})
 * @param resourceLoader the ResourceLoader to load application classes from
 * @param metadataSources the Hibernate MetadataSources service to use (e.g. reusing an existing one)
 * @since 4.3
 */
public LocalSessionFactoryBuilder(
		@Nullable DataSource dataSource, ResourceLoader resourceLoader, MetadataSources metadataSources) {

	super(metadataSources);

	getProperties().put(AvailableSettings.CURRENT_SESSION_CONTEXT_CLASS, SpringSessionContext.class.getName());
	if (dataSource != null) {
		getProperties().put(AvailableSettings.DATASOURCE, dataSource);
	}

	// Hibernate 5.1/5.2: manually enforce connection release mode ON_CLOSE (the former default)
	try {
		// Try Hibernate 5.2
		AvailableSettings.class.getField("CONNECTION_HANDLING");
		getProperties().put("hibernate.connection.handling_mode", "DELAYED_ACQUISITION_AND_HOLD");
	}
	catch (NoSuchFieldException ex) {
		// Try Hibernate 5.1
		try {
			AvailableSettings.class.getField("ACQUIRE_CONNECTIONS");
			getProperties().put("hibernate.connection.release_mode", "ON_CLOSE");
		}
		catch (NoSuchFieldException ex2) {
			// on Hibernate 5.0.x or lower - no need to change the default there
		}
	}

	getProperties().put(AvailableSettings.CLASSLOADERS, Collections.singleton(resourceLoader.getClassLoader()));
	this.resourcePatternResolver = ResourcePatternUtils.getResourcePatternResolver(resourceLoader);
}
 
Example #28
Source File: ConfigBean.java    From sailfish-core with Apache License 2.0 5 votes vote down vote up
public void applyConfig(Configuration configuration) {

			Properties prop = configuration.getProperties();

			try {
    			String url = prop.getProperty(AvailableSettings.URL, "");

    			URI full = new URI(url);
				URI uri = new URI(full.getSchemeSpecificPart());
				setProtocol(full.getScheme());
				setSubProtocol(uri.getScheme());
				setHost(uri.getHost());
				int intPort = uri.getPort();
                port = intPort == -1 ? "" : String.valueOf(intPort);
				path = uri.getPath().replace("/", "");
				query = uri.getQuery();
			} catch (URISyntaxException e) {
				logger.error("Could not parse hibernate url.", e);
			}

			driverClass = prop.getProperty(AvailableSettings.DRIVER);
			dialect = prop.getProperty(AvailableSettings.DIALECT);
			preferredTestQuery = prop.getProperty(PREFFERED_TEST_QUERY, "SELECT 1;");

			userName = prop.getProperty(AvailableSettings.USER, "sailfish");
			password = prop.getProperty(AvailableSettings.PASS, "999");

		}
 
Example #29
Source File: UnlimitedMessageColumnsMigration.java    From sailfish-core with Apache License 2.0 5 votes vote down vote up
public UnlimitedMessageColumnsMigration(Session session, Configuration configuration) throws URISyntaxException {
    this.session = session;
    String dialect = configuration.getProperty(AvailableSettings.DIALECT);
    this.nativeDbQueries = NativeDbQueries.fromDialect(dialect);
    String url = configuration.getProperty(AvailableSettings.URL);
    URI full = new URI(url);
    URI uri = new URI(full.getSchemeSpecificPart());
    this.databaseName = uri.getPath().replace("/", "");
}
 
Example #30
Source File: BootstrapContextImpl.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
public BootstrapContextImpl(
		StandardServiceRegistry serviceRegistry,
		MetadataBuildingOptions metadataBuildingOptions) {
	this.serviceRegistry = serviceRegistry;
	this.classmateContext = new ClassmateContext();
	this.metadataBuildingOptions = metadataBuildingOptions;

	final ClassLoaderService classLoaderService = serviceRegistry.getService( ClassLoaderService.class );
	this.classLoaderAccess = new ClassLoaderAccessImpl( classLoaderService );
	this.hcannReflectionManager = generateHcannReflectionManager();

	final StrategySelector strategySelector = serviceRegistry.getService( StrategySelector.class );
	final ConfigurationService configService = serviceRegistry.getService( ConfigurationService.class );

	this.jpaCompliance = new MutableJpaComplianceImpl( configService.getSettings(), false );
	this.scanOptions = new StandardScanOptions(
			(String) configService.getSettings().get( AvailableSettings.SCANNER_DISCOVERY ),
			false
	);

	// ScanEnvironment must be set explicitly
	this.scannerSetting = configService.getSettings().get( AvailableSettings.SCANNER );
	if ( this.scannerSetting == null ) {
		this.scannerSetting = configService.getSettings().get( AvailableSettings.SCANNER_DEPRECATED );
		if ( this.scannerSetting != null ) {
			DEPRECATION_LOGGER.logDeprecatedScannerSetting();
		}
	}
	this.archiveDescriptorFactory = strategySelector.resolveStrategy(
			ArchiveDescriptorFactory.class,
			configService.getSettings().get( AvailableSettings.SCANNER_ARCHIVE_INTERPRETER )
	);
	this.typeConfiguration = new TypeConfiguration();
}