org.hibernate.cfg.Environment Java Examples

The following examples show how to use org.hibernate.cfg.Environment. 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: HibernateUtil.java    From tutorials with 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 #2
Source File: EncryptedBinaryType.java    From jasypt with 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 #3
Source File: SQLExceptionConverterFactory.java    From cacheonix-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * 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 #4
Source File: LocalSessionFactoryBeanTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@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 #5
Source File: JpaConfig.java    From thymeleafexamples-layouts with 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 #6
Source File: Teradata14Dialect.java    From lams with 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 #7
Source File: ConfigHelper.java    From lams with 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 #8
Source File: SessionFactoryUtils.java    From lams with 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 #9
Source File: HibernateUtil.java    From tutorials with 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 #10
Source File: TransactionIsolationExternalDataSourceConnectionProviderTest.java    From hibernate-master-class with Apache License 2.0 6 votes vote down vote up
@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 #11
Source File: ReadWriteTest.java    From redisson with 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 #12
Source File: CatalogMultitenancyTest.java    From high-performance-java-persistence with Apache License 2.0 6 votes vote down vote up
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 #13
Source File: BatchBuilderInitiator.java    From lams with 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 #14
Source File: EnhancingClassTransformerImpl.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@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 #15
Source File: StandardServiceRegistryBuilder.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Create a builder with the specified bootstrap services.
 *
 * @param bootstrapServiceRegistry Provided bootstrap registry to use.
 */
public StandardServiceRegistryBuilder(
		BootstrapServiceRegistry bootstrapServiceRegistry,
		LoadedConfig loadedConfigBaseline) {
	this.settings = Environment.getProperties();
	this.bootstrapServiceRegistry = bootstrapServiceRegistry;
	this.configLoader = new ConfigLoader( bootstrapServiceRegistry );
	this.aggregatedCfgXml = loadedConfigBaseline;
}
 
Example #16
Source File: PersistenceModule.java    From nomulus with Apache License 2.0 5 votes vote down vote up
@VisibleForTesting
@Provides
@DefaultHibernateConfigs
public static ImmutableMap<String, String> provideDefaultDatabaseConfigs() {
  ImmutableMap.Builder<String, String> properties = ImmutableMap.builder();

  properties.put(Environment.DRIVER, "org.postgresql.Driver");
  properties.put(
      Environment.CONNECTION_PROVIDER,
      "org.hibernate.hikaricp.internal.HikariCPConnectionProvider");
  // Whether to automatically validate and export schema DDL to the database when the
  // SessionFactory is created. Setting it to 'none' to turn off the feature.
  properties.put(Environment.HBM2DDL_AUTO, "none");

  // Hibernate converts any date to this timezone when writing to the database.
  properties.put(Environment.JDBC_TIME_ZONE, "UTC");
  properties.put(
      Environment.PHYSICAL_NAMING_STRATEGY, NomulusNamingStrategy.class.getCanonicalName());

  properties.put(Environment.ISOLATION, getHibernateConnectionIsolation());
  properties.put(Environment.SHOW_SQL, getHibernateLogSqlQueries());
  properties.put(HIKARI_CONNECTION_TIMEOUT, getHibernateHikariConnectionTimeout());
  properties.put(HIKARI_MINIMUM_IDLE, getHibernateHikariMinimumIdle());
  properties.put(HIKARI_MAXIMUM_POOL_SIZE, getHibernateHikariMaximumPoolSize());
  properties.put(HIKARI_IDLE_TIMEOUT, getHibernateHikariIdleTimeout());
  properties.put(Environment.DIALECT, NomulusPostgreSQLDialect.class.getName());
  return properties.build();
}
 
Example #17
Source File: AbstractExecutable.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
public final void prepare() {
	Configuration cfg = new Configuration().setProperty( Environment.HBM2DDL_AUTO, "create-drop" );
	String[] resources = getResources();
	for ( int i = 0; i < resources.length; i++ ) {
		cfg.addResource( resources[i] );
	}
	factory = cfg.buildSessionFactory();
}
 
Example #18
Source File: Ingres10Dialect.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
private void registerDefaultProperties() {
	// true, false and unknown are now valid values
	// Remove the query substitutions previously added in IngresDialect.
	final Properties properties = getDefaultProperties();
	final String querySubst = properties.getProperty( Environment.QUERY_SUBSTITUTIONS );
	if ( querySubst != null ) {
		final String newQuerySubst = querySubst.replace( "true=1,false=0", "" );
		properties.setProperty( Environment.QUERY_SUBSTITUTIONS, newQuerySubst );
	}
}
 
Example #19
Source File: MultiTenancyJpaConfiguration.java    From multitenancy with GNU General Public License v2.0 5 votes vote down vote up
@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory(EntityManagerFactoryBuilder builder) {
	Map<String, Object> hibernateProps = new LinkedHashMap<>();
	hibernateProps.putAll(jpaProperties.getHibernateProperties(dataSource));

	hibernateProps.put(Environment.MULTI_TENANT, MultiTenancyStrategy.DATABASE);
	hibernateProps.put(Environment.MULTI_TENANT_CONNECTION_PROVIDER, multiTenantConnectionProvider);
	hibernateProps.put(Environment.MULTI_TENANT_IDENTIFIER_RESOLVER, currentTenantIdentifierResolver);
	hibernateProps.put(Environment.DIALECT, "org.hibernate.dialect.MySQLDialect");

	return builder.dataSource(dataSource).packages(Employee.class.getPackage().getName()).properties(hibernateProps).jta(false).build();
}
 
Example #20
Source File: HibernateUtil.java    From chipster with MIT License 5 votes vote down vote up
public void buildSessionFactory(List<Class<?>> hibernateClasses, Configuration config) {
	
	
	try {    		
		
		final org.hibernate.cfg.Configuration hibernateConf = new org.hibernate.cfg.Configuration();

		String dbDriver = config.getString("jobmanager", "hibernate-driver");
		String dbDialect = config.getString("jobmanager", "hibernate-dialect");
		String dbUrl = config.getString("jobmanager", "hibernate-url");
		String dbUsername = config.getString("jobmanager", "hibernate-username");
		String dbPassword = config.getString("jobmanager", "hibernate-password");		
		String showSql = config.getBoolean("jobmanager", "hibernate-show-sql") ? "true" : "false";
		String dbSchemaUpdate = config.getString("jobmanager", "hibernate-schema");

		hibernateConf.setProperty(Environment.DRIVER, dbDriver);
		hibernateConf.setProperty(Environment.URL, dbUrl);
		hibernateConf.setProperty(Environment.USER, dbUsername);
		hibernateConf.setProperty(Environment.PASS, dbPassword);
		hibernateConf.setProperty(Environment.DIALECT, dbDialect);
		hibernateConf.setProperty(Environment.SHOW_SQL, showSql);
		hibernateConf.setProperty(Environment.CURRENT_SESSION_CONTEXT_CLASS, "thread");
		hibernateConf.setProperty("hibernate.hbm2ddl.auto", dbSchemaUpdate);    		
		hibernateConf.setProperty("hibernate.c3p0.min_size", "3");
		
		for (Class<?> c : hibernateClasses) {
			hibernateConf.addAnnotatedClass(c);
		}    		    	   
		
		sessionFactory = hibernateConf.buildSessionFactory(
				new StandardServiceRegistryBuilder()
				.applySettings(hibernateConf.getProperties())
				.build());
 
	} catch (Throwable ex) {
		logger.log(Level.SEVERE, "sessionFactory creation failed.", ex);
		throw new ExceptionInInitializerError(ex);
	}
}
 
Example #21
Source File: LocalSessionFactoryBeanTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
@SuppressWarnings("serial")
public void testLocalSessionFactoryBeanWithCacheRegionFactory() throws Exception {
	final RegionFactory regionFactory = new NoCachingRegionFactory(null);
	final List invocations = new ArrayList();
	LocalSessionFactoryBean sfb = new LocalSessionFactoryBean() {
		@Override
		protected Configuration newConfiguration() {
			return new Configuration() {
				@Override
				public Configuration addInputStream(InputStream is) {
					try {
						is.close();
					}
					catch (IOException ex) {
					}
					invocations.add("addResource");
					return this;
				}
			};
		}
		@Override
		protected SessionFactory newSessionFactory(Configuration config) {
			assertEquals(LocalRegionFactoryProxy.class.getName(),
					config.getProperty(Environment.CACHE_REGION_FACTORY));
			assertSame(regionFactory, LocalSessionFactoryBean.getConfigTimeRegionFactory());
			invocations.add("newSessionFactory");
			return null;
		}
	};
	sfb.setCacheRegionFactory(regionFactory);
	sfb.afterPropertiesSet();
	assertTrue(sfb.getConfiguration() != null);
	assertEquals("newSessionFactory", invocations.get(0));
}
 
Example #22
Source File: LocalSessionFactoryBeanTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
@SuppressWarnings("serial")
public void testLocalSessionFactoryBeanWithTransactionAwareDataSource() throws Exception {
	final DriverManagerDataSource ds = new DriverManagerDataSource();
	final List invocations = new ArrayList();
	LocalSessionFactoryBean sfb = new LocalSessionFactoryBean() {
		@Override
		protected Configuration newConfiguration() {
			return new Configuration() {
				@Override
				public Configuration addInputStream(InputStream is) {
					try {
						is.close();
					}
					catch (IOException ex) {
					}
					invocations.add("addResource");
					return this;
				}
			};
		}

		@Override
		protected SessionFactory newSessionFactory(Configuration config) {
			assertEquals(TransactionAwareDataSourceConnectionProvider.class.getName(),
					config.getProperty(Environment.CONNECTION_PROVIDER));
			assertEquals(ds, LocalSessionFactoryBean.getConfigTimeDataSource());
			invocations.add("newSessionFactory");
			return null;
		}
	};
	sfb.setDataSource(ds);
	sfb.setUseTransactionAwareDataSource(true);
	sfb.afterPropertiesSet();
	assertTrue(sfb.getConfiguration() != null);
	assertEquals("newSessionFactory", invocations.get(0));
}
 
Example #23
Source File: JpaTransactionManagerRule.java    From nomulus with 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 #24
Source File: InvocationTargetExceptionTest.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
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 #25
Source File: LocalSessionFactoryBeanTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
@SuppressWarnings("serial")
public void testLocalSessionFactoryBeanWithDataSourceAndMappingJarLocations() throws Exception {
	final DriverManagerDataSource ds = new DriverManagerDataSource();
	final Set invocations = new HashSet();
	LocalSessionFactoryBean sfb = new LocalSessionFactoryBean() {
		@Override
		protected Configuration newConfiguration() {
			return new Configuration() {
				@Override
				public Configuration addJar(File file) {
					invocations.add("addResource " + file.getPath());
					return this;
				}
			};
		}

		@Override
		protected SessionFactory newSessionFactory(Configuration config) {
			assertEquals(LocalDataSourceConnectionProvider.class.getName(),
					config.getProperty(Environment.CONNECTION_PROVIDER));
			assertEquals(ds, LocalSessionFactoryBean.getConfigTimeDataSource());
			invocations.add("newSessionFactory");
			return null;
		}
	};
	sfb.setMappingJarLocations(new Resource[]{
			new FileSystemResource("mapping.hbm.jar"), new FileSystemResource("mapping2.hbm.jar")});
	sfb.setDataSource(ds);
	sfb.afterPropertiesSet();
	assertTrue(sfb.getConfiguration() != null);
	assertTrue(invocations.contains("addResource mapping.hbm.jar"));
	assertTrue(invocations.contains("addResource mapping2.hbm.jar"));
	assertTrue(invocations.contains("newSessionFactory"));
}
 
Example #26
Source File: LocalSessionFactoryBeanTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void testLocalSessionFactoryBeanWithInvalidProperties() throws Exception {
	LocalSessionFactoryBean sfb = new LocalSessionFactoryBean();
	sfb.setMappingResources(new String[0]);
	Properties prop = new Properties();
	prop.setProperty(Environment.CONNECTION_PROVIDER, "myClass");
	sfb.setHibernateProperties(prop);
	try {
		sfb.afterPropertiesSet();
	}
	catch (HibernateException ex) {
		// expected, provider class not found
	}
}
 
Example #27
Source File: QueryPlanCache.java    From lams with 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 #28
Source File: OptimisticTreeCacheProvider.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * 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 #29
Source File: LocalSessionFactoryBuilder.java    From spring4-understanding with Apache License 2.0 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
 */
@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 #30
Source File: EntityManagerFactoryProducer.java    From hibernate-demos with Apache License 2.0 5 votes vote down vote up
@Produces
@ApplicationScoped
public EntityManagerFactory produceEntityManagerFactory() {
    Map<String, Object> props = new HashMap<>();
    props.put("javax.persistence.bean.manager", beanManager);
    props.put(Environment.CONNECTION_PROVIDER, TransactionalConnectionProvider.class);
    return Persistence.createEntityManagerFactory(
            "myPu",
            props
    );
}