Java Code Examples for org.hibernate.cfg.Environment

The following examples show how to use org.hibernate.cfg.Environment. 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 want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: jasypt   Source File: EncryptedBinaryType.java    License: Apache License 2.0 6 votes vote down vote up
public void nullSafeSet(final PreparedStatement st, final Object value, final int index)
        throws HibernateException, SQLException {

    checkInitialization();
    
    if (value == null) {
        st.setNull(index, sqlType);
    } else {
        final byte[] encryptedValue = this.encryptor.encrypt((byte[]) value);
        if (Environment.useStreamsForBinary()) {
            st.setBinaryStream(
                    index, 
                    new ByteArrayInputStream(encryptedValue), 
                    encryptedValue.length);
        } else {
            st.setBytes(index, encryptedValue);
        }
    }
    
}
 
Example 2
Source Project: lams   Source File: SessionFactoryUtils.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Determine the DataSource of the given SessionFactory.
 * @param sessionFactory the SessionFactory to check
 * @return the DataSource, or {@code null} if none found
 * @see ConnectionProvider
 */
public static DataSource getDataSource(SessionFactory sessionFactory) {
	Method getProperties = ClassUtils.getMethodIfAvailable(sessionFactory.getClass(), "getProperties");
	if (getProperties != null) {
		Map<?, ?> props = (Map<?, ?>) ReflectionUtils.invokeMethod(getProperties, sessionFactory);
		Object dataSourceValue = props.get(Environment.DATASOURCE);
		if (dataSourceValue instanceof DataSource) {
			return (DataSource) dataSourceValue;
		}
	}
	if (sessionFactory instanceof SessionFactoryImplementor) {
		SessionFactoryImplementor sfi = (SessionFactoryImplementor) sessionFactory;
		try {
			ConnectionProvider cp = sfi.getServiceRegistry().getService(ConnectionProvider.class);
			if (cp != null) {
				return cp.unwrap(DataSource.class);
			}
		}
		catch (UnknownServiceException ex) {
			if (logger.isDebugEnabled()) {
				logger.debug("No ConnectionProvider found - cannot determine DataSource for SessionFactory: " + ex);
			}
		}
	}
	return null;
}
 
Example 3
Source Project: tutorials   Source File: HibernateUtil.java    License: MIT License 6 votes vote down vote up
public static SessionFactory getSessionFactory() {
    if (sessionFactory == null) {
        try {
            Configuration configuration = new Configuration();
            Properties settings = new Properties();
            settings.put(Environment.DRIVER, "org.hsqldb.jdbcDriver");
            settings.put(Environment.URL, "jdbc:hsqldb:mem:userrole");
            settings.put(Environment.USER, "sa");
            settings.put(Environment.PASS, "");
            settings.put(Environment.DIALECT, "org.hibernate.dialect.HSQLDialect");
            settings.put(Environment.SHOW_SQL, "true");
            settings.put(Environment.HBM2DDL_AUTO, "update");
            configuration.setProperties(settings);
            configuration.addAnnotatedClass(User.class);
            configuration.addAnnotatedClass(Role.class);

            ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
                    .applySettings(configuration.getProperties()).build();
            sessionFactory = configuration.buildSessionFactory(serviceRegistry);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    return sessionFactory;
}
 
Example 4
@Test
public void test() {
    Session session = null;
    Transaction txn = null;
    try {
        session = getSessionFactory().openSession();
        txn = session.beginTransaction();
        session.doWork(new Work() {
            @Override
            public void execute(Connection connection) throws SQLException {
                LOGGER.debug("Transaction isolation level is {}", Environment.isolationLevelToString(connection.getTransactionIsolation()));
            }
        });
        txn.commit();
    } catch (RuntimeException e) {
        if ( txn != null && txn.isActive() ) txn.rollback();
        throw e;
    } finally {
        if (session != null) {
            session.close();
        }
    }
}
 
Example 5
@Override
public byte[] transform(
		ClassLoader loader,
		String className,
		Class<?> classBeingRedefined,
		ProtectionDomain protectionDomain,
		byte[] classfileBuffer) throws IllegalClassFormatException {

	// The first design had the enhancer as a class variable. That approach had some goods and bads.
	// We don't had to create an enhancer for each class, but on the other end it would stay in memory forever.
	// It also assumed that all calls come from the same class loader, which is fair, but this makes it more robust.

	try {
		Enhancer enhancer = Environment.getBytecodeProvider().getEnhancer( new EnhancementContextWrapper( enhancementContext, loader ) );
		return enhancer.enhance( className, classfileBuffer );
	}
	catch (final Exception e) {
		throw new IllegalClassFormatException( "Error performing enhancement of " + className ) {
			@Override
			public synchronized Throwable getCause() {
				return e;
			}
		};
	}
}
 
Example 6
Source Project: lams   Source File: BatchBuilderInitiator.java    License: GNU General Public License v2.0 6 votes vote down vote up
@Override
public BatchBuilder initiateService(Map configurationValues, ServiceRegistryImplementor registry) {
	final Object builder = configurationValues.get( BUILDER );
	if ( builder == null ) {
		return new BatchBuilderImpl(
				ConfigurationHelper.getInt( Environment.STATEMENT_BATCH_SIZE, configurationValues, 1 )
		);
	}

	if ( BatchBuilder.class.isInstance( builder ) ) {
		return (BatchBuilder) builder;
	}

	final String builderClassName = builder.toString();
	try {
		return (BatchBuilder) registry.getService( ClassLoaderService.class ).classForName( builderClassName ).newInstance();
	}
	catch (Exception e) {
		throw new ServiceException( "Could not build explicit BatchBuilder [" + builderClassName + "]", e );
	}
}
 
Example 7
private void addTenantConnectionProvider(String tenantId) {
    DataSourceProvider dataSourceProvider = database().dataSourceProvider();

    Properties properties = properties();

    MysqlDataSource tenantDataSource = new MysqlDataSource();
    tenantDataSource.setDatabaseName(tenantId);
    tenantDataSource.setUser(dataSourceProvider.username());
    tenantDataSource.setPassword(dataSourceProvider.password());

    properties.put(
            Environment.DATASOURCE,
            dataSourceProxyType().dataSource(tenantDataSource)
    );

    addTenantConnectionProvider(tenantId, tenantDataSource, properties);
}
 
Example 8
Source Project: redisson   Source File: ReadWriteTest.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected void configure(Configuration cfg) {
    super.configure(cfg);
    cfg.setProperty(Environment.DRIVER, org.h2.Driver.class.getName());
    cfg.setProperty(Environment.URL, "jdbc:h2:mem:db1;DB_CLOSE_DELAY=-1;");
    cfg.setProperty(Environment.USER, "sa");
    cfg.setProperty(Environment.PASS, "");
    cfg.setProperty(Environment.CACHE_REGION_PREFIX, "");
    cfg.setProperty(Environment.GENERATE_STATISTICS, "true");

    cfg.setProperty(Environment.USE_SECOND_LEVEL_CACHE, "true");
    cfg.setProperty(Environment.USE_QUERY_CACHE, "true");
    cfg.setProperty(Environment.CACHE_REGION_FACTORY, RedissonRegionFactory.class.getName());
    
    cfg.setProperty("hibernate.cache.redisson.item.eviction.max_entries", "100");
    cfg.setProperty("hibernate.cache.redisson.item.expiration.time_to_live", "1500");
    cfg.setProperty("hibernate.cache.redisson.item.expiration.max_idle_time", "1000");
    
    cfg.setProperty("hibernate.cache.redisson.item##NaturalId.eviction.max_entries", "1000");
    cfg.setProperty("hibernate.cache.redisson.item##NaturalId.expiration.time_to_live", "1100");
    cfg.setProperty("hibernate.cache.redisson.item##NaturalId.expiration.max_idle_time", "1200");
}
 
Example 9
Source Project: lams   Source File: ConfigHelper.java    License: GNU General Public License v2.0 6 votes vote down vote up
public static InputStream getResourceAsStream(String resource) {
	String stripped = resource.startsWith( "/" )
			? resource.substring( 1 )
			: resource;

	InputStream stream = null;
	ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
	if ( classLoader != null ) {
		stream = classLoader.getResourceAsStream( stripped );
	}
	if ( stream == null ) {
		stream = Environment.class.getResourceAsStream( resource );
	}
	if ( stream == null ) {
		stream = Environment.class.getClassLoader().getResourceAsStream( stripped );
	}
	if ( stream == null ) {
		throw new HibernateException( resource + " not found" );
	}
	return stream;
}
 
Example 10
Source Project: lams   Source File: Teradata14Dialect.java    License: GNU General Public License v2.0 6 votes vote down vote up
public Teradata14Dialect() {
	super();
	//registerColumnType data types
	registerColumnType( Types.BIGINT, "BIGINT" );
	registerColumnType( Types.BINARY, "VARBYTE(100)" );
	registerColumnType( Types.LONGVARBINARY, "VARBYTE(32000)" );
	registerColumnType( Types.LONGVARCHAR, "VARCHAR(32000)" );

	getDefaultProperties().setProperty( Environment.USE_STREAMS_FOR_BINARY, "true" );
	getDefaultProperties().setProperty( Environment.STATEMENT_BATCH_SIZE, DEFAULT_BATCH_SIZE );

	registerFunction( "current_time", new SQLFunctionTemplate( StandardBasicTypes.TIME, "current_time" ) );
	registerFunction( "current_date", new SQLFunctionTemplate( StandardBasicTypes.DATE, "current_date" ) );

	TeraIndexExporter =  new TeradataIndexExporter( this );
}
 
Example 11
Source Project: thymeleafexamples-layouts   Source File: JpaConfig.java    License: Apache License 2.0 6 votes vote down vote up
@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory(DataSource dataSource) {
    LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
    entityManagerFactoryBean.setDataSource(dataSource);

    String entities = ClassUtils.getPackageName(Application.class);
    String converters = ClassUtils.getPackageName(Jsr310JpaConverters.class);
    entityManagerFactoryBean.setPackagesToScan(entities, converters);

    entityManagerFactoryBean.setJpaVendorAdapter(new HibernateJpaVendorAdapter());

    Properties jpaProperties = new Properties();
    jpaProperties.put(Environment.DIALECT, dialect);
    jpaProperties.put(Environment.HBM2DDL_AUTO, hbm2ddlAuto);
    jpaProperties.put(Environment.SHOW_SQL, showSql);
    jpaProperties.put(Environment.FORMAT_SQL, formatSql);
    jpaProperties.put(Environment.USE_SQL_COMMENTS, useSqlComments);
    entityManagerFactoryBean.setJpaProperties(jpaProperties);

    return entityManagerFactoryBean;
}
 
Example 12
/**
 * Build a SQLExceptionConverter instance.
 * <p/>
 * First, looks for a {@link Environment.SQL_EXCEPTION_CONVERTER} property to see
 * if the configuration specified the class of a specific converter to use.  If this
 * property is set, attempt to construct an instance of that class.  If not set, or
 * if construction fails, the converter specific to the dialect will be used.
 *
 * @param dialect    The defined dialect.
 * @param properties The configuration properties.
 * @return An appropriate SQLExceptionConverter instance.
 * @throws HibernateException There was an error building the SQLExceptionConverter.
 */
public static SQLExceptionConverter buildSQLExceptionConverter(Dialect dialect, Properties properties) throws HibernateException {
	SQLExceptionConverter converter = null;

	String converterClassName = ( String ) properties.get( Environment.SQL_EXCEPTION_CONVERTER );
	if ( StringHelper.isNotEmpty( converterClassName ) ) {
		converter = constructConverter( converterClassName, dialect.getViolatedConstraintNameExtracter() );
	}

	if ( converter == null ) {
		log.trace( "Using dialect defined converter" );
		converter = dialect.buildSQLExceptionConverter();
	}

	if ( converter instanceof Configurable ) {
		try {
			( ( Configurable ) converter ).configure( properties );
		}
		catch ( HibernateException e ) {
			log.warn( "Unable to configure SQLExceptionConverter", e );
			throw e;
		}
	}

	return converter;
}
 
Example 13
@Test
public void testLocalSessionFactoryBeanWithValidProperties() throws Exception {
	final Set invocations = new HashSet();
	LocalSessionFactoryBean sfb = new LocalSessionFactoryBean() {
		@Override
		protected SessionFactory newSessionFactory(Configuration config) {
			assertEquals(UserSuppliedConnectionProvider.class.getName(),
					config.getProperty(Environment.CONNECTION_PROVIDER));
			assertEquals("myValue", config.getProperty("myProperty"));
			invocations.add("newSessionFactory");
			return null;
		}
	};
	Properties prop = new Properties();
	prop.setProperty(Environment.CONNECTION_PROVIDER, UserSuppliedConnectionProvider.class.getName());
	prop.setProperty("myProperty", "myValue");
	sfb.setHibernateProperties(prop);
	sfb.afterPropertiesSet();
	assertTrue(sfb.getConfiguration() != null);
	assertTrue(invocations.contains("newSessionFactory"));
}
 
Example 14
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 15
/**
 * Create a builder with the specified bootstrap services.
 *
 * @param bootstrapServiceRegistry Provided bootstrap registry to use.
 */
public ReactiveServiceRegistryBuilder(
        BootstrapServiceRegistry bootstrapServiceRegistry,
        LoadedConfig loadedConfigBaseline) {
    this.settings = Environment.getProperties();
    this.bootstrapServiceRegistry = bootstrapServiceRegistry;
    this.configLoader = new ConfigLoader( bootstrapServiceRegistry );
    this.aggregatedCfgXml = loadedConfigBaseline;
    this.initiators = defaultReactiveInitiatorList();
}
 
Example 16
/**
 * Callback to perform any necessary initialization of the underlying cache implementation during SessionFactory
 * construction.
 *
 * @param properties current configuration settings.
 */
public final void start(Properties properties) throws CacheException {
	String jndiNamespace = properties.getProperty( Environment.CACHE_NAMESPACE );
	if ( StringHelper.isEmpty( jndiNamespace ) ) {
		throw new CacheException( "No JNDI namespace specified for cache" );
	}
	cache = locateCache( jndiNamespace, NamingHelper.getJndiProperties( properties ) );
	prepare( properties );
}
 
Example 17
Source Project: nomulus   Source File: JpaTransactionManagerRule.java    License: Apache License 2.0 5 votes vote down vote up
/** Constructs the {@link EntityManagerFactory} instance. */
private EntityManagerFactory createEntityManagerFactory(
    String jdbcUrl,
    String username,
    String password,
    ImmutableMap<String, String> configs,
    ImmutableList<Class> extraEntityClasses) {
  HashMap<String, String> properties = Maps.newHashMap(configs);
  properties.put(Environment.URL, jdbcUrl);
  properties.put(Environment.USER, username);
  properties.put(Environment.PASS, password);
  // Tell Postgresql JDBC driver to expect out-of-band schema change.
  properties.put("hibernate.hikari.dataSource.autosave", "conservative");

  ParsedPersistenceXmlDescriptor descriptor =
      PersistenceXmlUtility.getParsedPersistenceXmlDescriptor();

  // If we don't include the nomulus schema, remove all entity classes in the descriptor but keep
  // other settings like the converter classes.
  if (!includeNomulusSchema) {
    List<String> nonEntityClasses =
        descriptor.getManagedClassNames().stream()
            .filter(
                classString -> {
                  try {
                    return !Class.forName(classString).isAnnotationPresent(Entity.class);
                  } catch (ClassNotFoundException e) {
                    throw new IllegalArgumentException(e);
                  }
                })
            .collect(toImmutableList());
    descriptor.getManagedClassNames().clear();
    descriptor.getManagedClassNames().addAll(nonEntityClasses);
  }

  extraEntityClasses.stream().map(Class::getName).forEach(descriptor::addClasses);
  return Bootstrap.getEntityManagerFactoryBuilder(descriptor, properties).build();
}
 
Example 18
Source Project: java-11-examples   Source File: HibernateUtil.java    License: Apache License 2.0 5 votes vote down vote up
public static Properties getPostgresql10Properties() {
    Properties properties = new Properties();
    properties.put(Environment.DRIVER, "org.postgresql.Driver");
    // jdbc:postgresql://host:port/database
    properties.put(Environment.URL, "jdbc:postgresql://127.0.0.1:5432/userdata");
    properties.put(Environment.USER, "juraj");
    properties.put(Environment.PASS, "secret");
    properties.put(Environment.DIALECT, "org.hibernate.dialect.PostgreSQL10Dialect");
    properties.put(Environment.SHOW_SQL, "true");
    properties.put(Environment.CURRENT_SESSION_CONTEXT_CLASS, "thread");
    properties.put(Environment.HBM2DDL_AUTO, "update");
    return properties;
}
 
Example 19
/**
 * 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
 */
@SuppressWarnings("deprecation")  // to be able to build against Hibernate 4.3
public LocalSessionFactoryBuilder(DataSource dataSource, ResourceLoader resourceLoader) {
	getProperties().put(Environment.CURRENT_SESSION_CONTEXT_CLASS, SpringSessionContext.class.getName());
	if (dataSource != null) {
		getProperties().put(Environment.DATASOURCE, dataSource);
	}
	// APP_CLASSLOADER is deprecated as of Hibernate 4.3 but we need to remain compatible with 4.0+
	getProperties().put(AvailableSettings.APP_CLASSLOADER, resourceLoader.getClassLoader());
	this.resourcePatternResolver = ResourcePatternUtils.getResourcePatternResolver(resourceLoader);
}
 
Example 20
Source Project: redisson   Source File: CollectionTest.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected void configure(Configuration cfg) {
    super.configure(cfg);
    cfg.setProperty(Environment.DRIVER, org.h2.Driver.class.getName());
    cfg.setProperty(Environment.URL, "jdbc:h2:mem:db1;DB_CLOSE_DELAY=-1;");
    cfg.setProperty(Environment.USER, "sa");
    cfg.setProperty(Environment.PASS, "");
    cfg.setProperty(Environment.CACHE_REGION_PREFIX, "");
    cfg.setProperty(Environment.GENERATE_STATISTICS, "true");

    cfg.setProperty(Environment.SHOW_SQL, "true");
    cfg.setProperty(Environment.USE_SECOND_LEVEL_CACHE, "true");
    cfg.setProperty(Environment.USE_QUERY_CACHE, "true");
    cfg.setProperty(Environment.CACHE_REGION_FACTORY, RedissonRegionFactory.class.getName());
}
 
Example 21
Source Project: lams   Source File: PojoComponentTuplizer.java    License: GNU General Public License v2.0 5 votes vote down vote up
public PojoComponentTuplizer(Component component) {
	super( component );

	String[] getterNames = new String[propertySpan];
	String[] setterNames = new String[propertySpan];
	Class[] propTypes = new Class[propertySpan];
	for ( int i = 0; i < propertySpan; i++ ) {
		getterNames[i] = getters[i].getMethodName();
		setterNames[i] = setters[i].getMethodName();
		propTypes[i] = getters[i].getReturnType();
	}

	final String parentPropertyName = component.getParentProperty();
	if ( parentPropertyName == null ) {
		parentSetter = null;
		parentGetter = null;
	}
	else {
		final PropertyAccess propertyAccess = PropertyAccessStrategyBasicImpl.INSTANCE.buildPropertyAccess(
				componentClass,
				parentPropertyName
		);
		parentSetter = propertyAccess.getSetter();
		parentGetter = propertyAccess.getGetter();
	}

	if ( hasCustomAccessors || !Environment.useReflectionOptimizer() ) {
		optimizer = null;
	}
	else {
		// TODO: here is why we need to make bytecode provider global :(
		// TODO : again, fix this after HHH-1907 is complete
		optimizer = Environment.getBytecodeProvider().getReflectionOptimizer(
				componentClass, getterNames, setterNames, propTypes
		);
	}
}
 
Example 22
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
    resourcePatternResolver = ResourcePatternUtils.getResourcePatternResolver(applicationContext);
    String dsName = ConnectionSource.DEFAULT.equals(dataSourceName) ? "dataSource" : "dataSource_" + dataSourceName;
    Properties properties = getProperties();

    if(applicationContext.containsBean(dsName)) {
        properties.put(Environment.DATASOURCE, applicationContext.getBean(dsName));
    }
    properties.put(Environment.CURRENT_SESSION_CONTEXT_CLASS, currentSessionContext.getName());
    properties.put(AvailableSettings.CLASSLOADERS, applicationContext.getClassLoader());
}
 
Example 23
@Bean
public DataSource dataSource() {
    DriverManagerDataSource db = new DriverManagerDataSource();
    db.setDriverClassName(env.getProperty(Environment.DRIVER, jdbcDriver.class.getName()));
    db.setUrl(env.getProperty(Environment.URL, "jdbc:hsqldb:mem:test"));
    db.setUsername(env.getProperty(Environment.USER, "SA"));
    db.setPassword(env.getProperty(Environment.PASS, ""));
    return db;
}
 
Example 24
/**
 * Prepare the underlying JBossCache TreeCache instance.
 *
 * @param properties All current config settings.
 * @throws CacheException
 *          Indicates a problem preparing cache for use.
 */
public void start(Properties properties) {
	String resource = properties.getProperty( Environment.CACHE_PROVIDER_CONFIG );
	if (resource == null) {
		resource = properties.getProperty( CONFIG_RESOURCE );
	}
	if ( resource == null ) {
		resource = DEFAULT_CONFIG;
	}
	log.debug( "Configuring TreeCache from resource [" + resource + "]" );
	try {
		cache = new org.jboss.cache.TreeCache();
		PropertyConfigurator config = new PropertyConfigurator();
		config.configure( cache, resource );
		TransactionManagerLookup transactionManagerLookup =
				TransactionManagerLookupFactory.getTransactionManagerLookup( properties );
		if ( transactionManagerLookup == null ) {
			throw new CacheException(
					"JBossCache only supports optimisitc locking with a configured " +
					"TransactionManagerLookup (" + Environment.TRANSACTION_MANAGER_STRATEGY + ")"
			);
		}
		cache.setTransactionManagerLookup(
				new TransactionManagerLookupAdaptor(
						transactionManagerLookup,
						properties
				)
		);
		if ( ! NODE_LOCKING_SCHEME.equalsIgnoreCase( cache.getNodeLockingScheme() ) ) {
			log.info( "Overriding node-locking-scheme to : " + NODE_LOCKING_SCHEME );
			cache.setNodeLockingScheme( NODE_LOCKING_SCHEME );
		}
		cache.start();
	}
	catch ( Exception e ) {
		throw new CacheException( e );
	}
}
 
Example 25
Source Project: lams   Source File: QueryPlanCache.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Constructs the QueryPlanCache to be used by the given SessionFactory
 *
 * @param factory The SessionFactory
 */
@SuppressWarnings("deprecation")
public QueryPlanCache(final SessionFactoryImplementor factory) {
	this.factory = factory;

	Integer maxParameterMetadataCount = ConfigurationHelper.getInteger(
			Environment.QUERY_PLAN_CACHE_PARAMETER_METADATA_MAX_SIZE,
			factory.getProperties()
	);
	if ( maxParameterMetadataCount == null ) {
		maxParameterMetadataCount = ConfigurationHelper.getInt(
				Environment.QUERY_PLAN_CACHE_MAX_STRONG_REFERENCES,
				factory.getProperties(),
				DEFAULT_PARAMETER_METADATA_MAX_COUNT
		);
	}
	Integer maxQueryPlanCount = ConfigurationHelper.getInteger(
			Environment.QUERY_PLAN_CACHE_MAX_SIZE,
			factory.getProperties()
	);
	if ( maxQueryPlanCount == null ) {
		maxQueryPlanCount = ConfigurationHelper.getInt(
				Environment.QUERY_PLAN_CACHE_MAX_SOFT_REFERENCES,
				factory.getProperties(),
				DEFAULT_QUERY_PLAN_MAX_COUNT
		);
	}

	queryPlanCache = new BoundedConcurrentHashMap( maxQueryPlanCount, 20, BoundedConcurrentHashMap.Eviction.LIRS );
	parameterMetadataCache = new BoundedConcurrentHashMap<>(
			maxParameterMetadataCount,
			20,
			BoundedConcurrentHashMap.Eviction.LIRS
	);

	nativeQueryInterpreter = factory.getServiceRegistry().getService( NativeQueryInterpreter.class );
}
 
Example 26
public void testProxiedInvocationException() {
	if ( ! ( Environment.getBytecodeProvider() instanceof org.hibernate.bytecode.cglib.BytecodeProviderImpl ) ) {
		// because of the scoping :(
		reportSkip( "env not configured for cglib provider", "bytecode-provider InvocationTargetException handling" );
		return;
	}
	Session s = openSession();
	s.beginTransaction();
	Bean bean = new Bean();
	bean.setSomeString( "my-bean" );
	s.save( bean );
	s.getTransaction().commit();
	s.close();

	s = openSession();
	s.beginTransaction();
	bean = ( Bean ) s.load( Bean.class, bean.getSomeString() );
	assertFalse( Hibernate.isInitialized( bean ) );
	try {
		bean.throwException();
		fail( "exception not thrown" );
	}
	catch ( ParseException e ) {
		// expected behavior
	}
	catch( Throwable t ) {
		fail( "unexpected exception type : " + t );
	}

	s.delete( bean );
	s.getTransaction().commit();
	s.close();
}
 
Example 27
Source Project: nomulus   Source File: JpaTransactionManagerRule.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Drops and recreates the 'public' schema and all tables, then creates a new {@link
 * EntityManagerFactory} and save it in {@link #emf}.
 */
private void recreateSchema() throws Exception {
  if (emf != null) {
    emf.close();
    emf = null;
    emfEntityHash = 0;
    assertReasonableNumDbConnections();
  }
  executeSql(readSqlInClassPath(DB_CLEANUP_SQL_PATH));
  initScriptPath.ifPresent(path -> executeSql(readSqlInClassPath(path)));
  if (!extraEntityClasses.isEmpty()) {
    File tempSqlFile = File.createTempFile("tempSqlFile", ".sql");
    tempSqlFile.deleteOnExit();
    exporter.export(extraEntityClasses, tempSqlFile);
    executeSql(
        new String(Files.readAllBytes(tempSqlFile.toPath()), StandardCharsets.UTF_8));
  }

  ImmutableMap properties = PersistenceModule.provideDefaultDatabaseConfigs();
  if (!userProperties.isEmpty()) {
    // If there are user properties, create a new properties object with these added.
    Map<String, String> mergedProperties = Maps.newHashMap();
    mergedProperties.putAll(properties);
    mergedProperties.putAll(userProperties);
    properties = ImmutableMap.copyOf(mergedProperties);
  }
  // Forbid Hibernate push to stay consistent with flyway-based schema management.
  checkState(
      Objects.equals(properties.get(Environment.HBM2DDL_AUTO), "none"),
      "The HBM2DDL_AUTO property must be 'none'.");
  assertReasonableNumDbConnections();
  emf =
      createEntityManagerFactory(
          getJdbcUrl(),
          database.getUsername(),
          database.getPassword(),
          properties,
          extraEntityClasses);
  emfEntityHash = entityHash;
}
 
Example 28
@Override
public boolean useStreamForLobBinding() {
	if ( useStreamForLobBinding == null ) {
		useStreamForLobBinding = Environment.useStreamsForBinary()
				|| getJdbcServices().getJdbcEnvironment().getDialect().useInputStreamToInsertBlob();
	}
	return useStreamForLobBinding;
}
 
Example 29
@Bean
public Properties hibernateProperties() {
    return new Properties() {
        {
            setProperty(Environment.DIALECT, env.getProperty(Environment.DIALECT, HSQLDialect.class.getName()));
            setProperty(Environment.HBM2DDL_AUTO, env.getProperty(Environment.HBM2DDL_AUTO));
        }
    };
}
 
Example 30
Source Project: redisson   Source File: TransactionalTest.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected void configure(Configuration cfg) {
    super.configure(cfg);
    cfg.setProperty(Environment.DRIVER, org.h2.Driver.class.getName());
    cfg.setProperty(Environment.URL, "jdbc:h2:mem:db1;DB_CLOSE_DELAY=-1;");
    cfg.setProperty(Environment.USER, "sa");
    cfg.setProperty(Environment.PASS, "");
    cfg.setProperty(Environment.CACHE_REGION_PREFIX, "");
    cfg.setProperty(Environment.GENERATE_STATISTICS, "true");

    cfg.setProperty(Environment.USE_SECOND_LEVEL_CACHE, "true");
    cfg.setProperty(Environment.USE_QUERY_CACHE, "true");
    cfg.setProperty(Environment.CACHE_REGION_FACTORY, RedissonRegionFactory.class.getName());
}