Java Code Examples for org.hibernate.cfg.Configuration#setProperties()

The following examples show how to use org.hibernate.cfg.Configuration#setProperties() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: tutorials   File: NamingStrategyLiveTest.java    License: MIT License 6 votes vote down vote up
@Before
public void init() {
    try {
        Configuration configuration = new Configuration();

        Properties properties = new Properties();
        properties.load(Thread.currentThread()
            .getContextClassLoader()
            .getResourceAsStream("hibernate-namingstrategy.properties"));

        configuration.setProperties(properties);

        ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties())
            .build();
        MetadataSources metadataSources = new MetadataSources(serviceRegistry);
        metadataSources.addAnnotatedClass(Customer.class);

        SessionFactory factory = metadataSources.buildMetadata()
            .buildSessionFactory();

        session = factory.openSession();
    } catch (HibernateException | IOException e) {
        fail("Failed to initiate Hibernate Session [Exception:" + e.toString() + "]");
    }
}
 
Example 2
Source Project: yeti   File: HibernateUtil.java    License: MIT License 6 votes vote down vote up
private static SessionFactory buildSessionAnnotationFactory() {
    try {
        Properties dbProps = ConfigSettings.getDatabaseProperties();
        
        Configuration configuration = new Configuration();
        configuration.setProperties(dbProps);
        configuration.configure("hibernate-annotation.cfg.xml");

        ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();

        sessionFactory = configuration.buildSessionFactory(serviceRegistry);

        return sessionFactory;
    } catch (HibernateException ex) {
        Logger.getLogger(HibernateUtil.class.getName()).log(Level.SEVERE, null, ex);
        throw new ExceptionInInitializerError(ex);
    }
}
 
Example 3
Source Project: tutorials   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
Source Project: tutorials   File: HibernateUtil.java    License: MIT License 6 votes vote down vote up
public static SessionFactory getSessionFactory() {
    try {
        Properties properties = getProperties();
        Configuration configuration = new Configuration();
        configuration.setProperties(properties);
        configuration.addAnnotatedClass(Person.class);
        configuration.addAnnotatedClass(Address.class);
        ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
                .applySettings(configuration.getProperties()).build();
        sessionFactory = configuration.buildSessionFactory(serviceRegistry);
        return sessionFactory;
    } catch (IOException e) {
        e.printStackTrace();
    }
    return sessionFactory;
}
 
Example 5
Source Project: tutorials   File: PersistJSONUnitTest.java    License: MIT License 6 votes vote down vote up
@Before
public void init() {
    try {
        Configuration configuration = new Configuration();

        Properties properties = new Properties();
        properties.load(Thread.currentThread()
            .getContextClassLoader()
            .getResourceAsStream("hibernate-persistjson.properties"));

        configuration.setProperties(properties);

        ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties())
            .build();
        MetadataSources metadataSources = new MetadataSources(serviceRegistry);
        metadataSources.addAnnotatedClass(Customer.class);

        SessionFactory factory = metadataSources.buildMetadata()
            .buildSessionFactory();

        session = factory.openSession();
    } catch (HibernateException | IOException e) {
        fail("Failed to initiate Hibernate Session [Exception:" + e.toString() + "]");
    }
}
 
Example 6
Source Project: java-11-examples   File: HibernateUtil.java    License: Apache License 2.0 5 votes vote down vote up
public static SessionFactory getSessionFactory(Properties properties) {
    Configuration configuration = new Configuration();

    configuration.setProperties(properties);
    configuration.addAnnotatedClass(UserData.class);
    ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
            .applySettings(configuration.getProperties()).build();
    return configuration.buildSessionFactory(serviceRegistry);
}
 
Example 7
Source Project: hibernate-types   File: AbstractTest.java    License: Apache License 2.0 5 votes vote down vote up
private SessionFactory newSessionFactory() {
    Properties properties = properties();
    Configuration configuration = new Configuration().addProperties(properties);
    for (Class<?> entityClass : entities()) {
        configuration.addAnnotatedClass(entityClass);
    }
    String[] packages = packages();
    if (packages != null) {
        for (String scannedPackage : packages) {
            configuration.addPackage(scannedPackage);
        }
    }
    String[] resources = resources();
    if (resources != null) {
        for (String resource : resources) {
            configuration.addResource(resource);
        }
    }
    Interceptor interceptor = interceptor();
    if (interceptor != null) {
        configuration.setInterceptor(interceptor);
    }
    configuration.setProperties(properties);
    return configuration.buildSessionFactory(
            new BootstrapServiceRegistryBuilder()
                    .build()
    );
}
 
Example 8
Source Project: journaldev   File: HibernateUtil.java    License: MIT License 5 votes vote down vote up
private static SessionFactory buildSessionJavaConfigFactory() {
   	try {
   	Configuration configuration = new Configuration();
	
	//Create Properties, can be read from property files too
	Properties props = new Properties();
	props.put("hibernate.connection.driver_class", "com.mysql.jdbc.Driver");
	props.put("hibernate.connection.url", "jdbc:mysql://localhost/TestDB");
	props.put("hibernate.connection.username", "pankaj");
	props.put("hibernate.connection.password", "pankaj123");
	props.put("hibernate.current_session_context_class", "thread");
	
	configuration.setProperties(props);
	
	//we can set mapping file or class with annotation
	//addClass(Employee1.class) will look for resource
	// com/journaldev/hibernate/model/Employee1.hbm.xml (not good)
	configuration.addAnnotatedClass(Employee1.class);
	
	ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
   	System.out.println("Hibernate Java Config serviceRegistry created");
   	
   	SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry);
   	
       return sessionFactory;
   	}
       catch (Throwable ex) {
           System.err.println("Initial SessionFactory creation failed." + ex);
           throw new ExceptionInInitializerError(ex);
       }
}
 
Example 9
private SchemaExport getSchemaExport(Configuration cfg) throws HibernateException, IOException {
	Properties properties = new Properties();
	properties.putAll( cfg.getProperties() );
	if (propertiesFile == null) {
		properties.putAll( getProject().getProperties() );
	}
	else {
		properties.load( new FileInputStream(propertiesFile) );
	}
	cfg.setProperties(properties);
	return new SchemaExport(cfg)
			.setHaltOnError(haltOnError)
			.setOutputFile( outputFile.getPath() )
			.setDelimiter(delimiter);
}
 
Example 10
private SchemaUpdate getSchemaUpdate(Configuration cfg) throws HibernateException, IOException {
	Properties properties = new Properties();
	properties.putAll( cfg.getProperties() );
	if (propertiesFile == null) {
		properties.putAll( getProject().getProperties() );
	}
	else {
		properties.load( new FileInputStream(propertiesFile) );
	}
	cfg.setProperties(properties);
	return new SchemaUpdate(cfg);
}
 
Example 11
public static void main(String[] args) {
	try {
		Configuration cfg = new Configuration();

		String propFile = null;

		for ( int i = 0; i < args.length; i++ ) {
			if ( args[i].startsWith( "--" ) ) {
				if ( args[i].startsWith( "--properties=" ) ) {
					propFile = args[i].substring( 13 );
				}
				else if ( args[i].startsWith( "--config=" ) ) {
					cfg.configure( args[i].substring( 9 ) );
				}
				else if ( args[i].startsWith( "--naming=" ) ) {
					cfg.setNamingStrategy(
							( NamingStrategy ) ReflectHelper.classForName( args[i].substring( 9 ) ).newInstance()
					);
				}
			}
			else {
				cfg.addFile( args[i] );
			}

		}

		if ( propFile != null ) {
			Properties props = new Properties();
			props.putAll( cfg.getProperties() );
			props.load( new FileInputStream( propFile ) );
			cfg.setProperties( props );
		}

		new SchemaValidator( cfg ).validate();
	}
	catch ( Exception e ) {
		log.error( "Error running schema update", e );
		e.printStackTrace();
	}
}
 
Example 12
private SchemaValidator getSchemaValidator(Configuration cfg) throws HibernateException, IOException {
	Properties properties = new Properties();
	properties.putAll( cfg.getProperties() );
	if (propertiesFile == null) {
		properties.putAll( getProject().getProperties() );
	}
	else {
		properties.load( new FileInputStream(propertiesFile) );
	}
	cfg.setProperties(properties);
	return new SchemaValidator(cfg);
}
 
Example 13
public static synchronized SessionFactory getSessionFactory() {
  if (sessionFactory == null) {
    try {
      Configuration configuration = new Configuration();
      Properties settings = new Properties();
      settings.put(Environment.DRIVER, "org.h2.Driver");
      settings.put(Environment.URL, "jdbc:h2:mem:test_mem");
      settings.put(Environment.USER, "sa");
      settings.put(Environment.PASS, "sa");
      settings.put(Environment.DIALECT, "org.hibernate.dialect.H2Dialect");
      settings.put(Environment.SHOW_SQL, "true");
      settings.put(Environment.CURRENT_SESSION_CONTEXT_CLASS, "thread");
      settings.put(Environment.HBM2DDL_AUTO, "create-drop");
      configuration.setProperties(settings);

      configuration.addAnnotatedClass(Category.class);
      configuration.addAnnotatedClass(Author.class);
      configuration.addAnnotatedClass(Book.class);

      ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
          .applySettings(configuration.getProperties()).build();

      sessionFactory = configuration.buildSessionFactory(serviceRegistry);
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
  return sessionFactory;
}
 
Example 14
protected Configuration getConfiguration(Properties prop) {
    Configuration config = new Configuration();
    Properties properties = new Properties();
    properties.putAll(getDefaultProperties());
    if (prop != null) {
        properties.putAll(prop);
    }
    config.setProperties(properties);

    config.addAnnotatedClass(Person.class);
    config.addAnnotatedClass(Contact.class);
    config.addAnnotatedClass(Book.class);

    return config;
}
 
Example 15
@Provides
@Singleton
public SessionFactory sessionFactory() {
  try {
    Configuration configuration = new Configuration();
    configuration.addAnnotatedClass(AlarmDb.class);
    configuration.addAnnotatedClass(AlarmDefinitionDb.class);
    configuration.addAnnotatedClass(AlarmMetricDb.class);
    configuration.addAnnotatedClass(MetricDefinitionDb.class);
    configuration.addAnnotatedClass(MetricDefinitionDimensionsDb.class);
    configuration.addAnnotatedClass(MetricDimensionDb.class);
    configuration.addAnnotatedClass(SubAlarmDefinitionDb.class);
    configuration.addAnnotatedClass(SubAlarmDefinitionDimensionDb.class);
    configuration.addAnnotatedClass(SubAlarmDb.class);
    configuration.addAnnotatedClass(AlarmActionDb.class);
    configuration.addAnnotatedClass(NotificationMethodDb.class);

    // retrieve hikari properties for right driver
    configuration.setProperties(this.getHikariProperties(this.dbConfig.getDriverClass()));

    final ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
        .applySettings(configuration.getProperties())
        .build();

    // builds a session factory from the service registry
    return configuration.buildSessionFactory(serviceRegistry);
  } catch (Throwable ex) {
    throw new ProvisionException("Failed to provision Hibernate DB", ex);
  }
}
 
Example 16
private final SessionFactory configureSessionFactory() throws IOException {
    final Configuration configuration = new Configuration();
    final InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("hibernate-mysql.properties");
    final Properties hibernateProperties = new Properties();
    hibernateProperties.load(inputStream);
    configuration.setProperties(hibernateProperties);

    configuration.addAnnotatedClass(Foo.class);

    final ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
    final SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry);
    return sessionFactory;
}
 
Example 17
public static void main(String[] args) {
	try {
		Configuration cfg = new Configuration();
		String outFile = null;

		boolean script = true;
		// If true then execute db updates, otherwise just generate and
		// display updates
		boolean doUpdate = true;
		String propFile = null;

		for (int i = 0; i < args.length; i++) {
			if (args[i].startsWith("--")) {
				if (args[i].equals("--quiet")) {
					script = false;
				} else if (args[i].startsWith("--properties=")) {
					propFile = args[i].substring(13);
				} else if (args[i].startsWith("--config=")) {
					cfg.configure(args[i].substring(9));
				} else if (args[i].startsWith("--text")) {
					doUpdate = false;
				} else if (args[i].startsWith("--naming=")) {
					cfg.setNamingStrategy((NamingStrategy) ReflectHelper.classForName(
							args[i].substring(9)).newInstance());
				} else if (args[i].startsWith("--output=")) {
					outFile = args[i].substring(9);
				}
			} else {
				cfg.addFile(args[i]);
			}

		}

		if (propFile != null) {
			Properties props = new Properties();
			props.putAll(cfg.getProperties());
			props.load(new FileInputStream(propFile));
			cfg.setProperties(props);
		}

		new SchemaUpdate(cfg).setOutputFile(outFile).execute(script, doUpdate);
	} catch (Exception e) {
		log.error("Error running schema update", e);
		e.printStackTrace();
	}
}
 
Example 18
Source Project: modeldb   File: ModelDBHibernateUtil.java    License: Apache License 2.0 4 votes vote down vote up
public static SessionFactory createOrGetSessionFactory() throws ModelDBException {
  if (sessionFactory == null) {
    LOGGER.info("Fetching sessionFactory");
    try {
      App app = App.getInstance();
      Map<String, Object> databasePropMap = app.getDatabasePropMap();

      Map<String, Object> rDBPropMap =
          (Map<String, Object>) databasePropMap.get("RdbConfiguration");

      databaseName = (String) rDBPropMap.get("RdbDatabaseName");
      if (!app.getTraceEnabled()) {
        rDBDriver = (String) rDBPropMap.get("RdbDriver");
      } else {
        rDBDriver = "io.opentracing.contrib.jdbc.TracingDriver";
      }
      rDBUrl = (String) rDBPropMap.get("RdbUrl");
      rDBDialect = (String) rDBPropMap.get("RdbDialect");
      configUsername = (String) rDBPropMap.get("RdbUsername");
      configPassword = (String) rDBPropMap.get("RdbPassword");
      if (databasePropMap.containsKey("timeout")) {
        timeout = (Integer) databasePropMap.get("timeout");
      }
      liquibaseLockThreshold =
          Long.parseLong(databasePropMap.getOrDefault("liquibaseLockThreshold", "60").toString());

      // Change liquibase default table names
      System.getProperties().put("liquibase.databaseChangeLogTableName", "database_change_log");
      System.getProperties()
          .put("liquibase.databaseChangeLogLockTableName", "database_change_log_lock");

      // Hibernate settings equivalent to hibernate.cfg.xml's properties
      Configuration configuration = new Configuration();

      Properties settings = new Properties();

      String connectionString =
          rDBUrl
              + "/"
              + databaseName
              + "?createDatabaseIfNotExist=true&useUnicode=yes&characterEncoding=UTF-8";
      settings.put(Environment.DRIVER, rDBDriver);
      settings.put(Environment.URL, connectionString);
      settings.put(Environment.USER, configUsername);
      settings.put(Environment.PASS, configPassword);
      settings.put(Environment.DIALECT, rDBDialect);
      settings.put(Environment.HBM2DDL_AUTO, "validate");
      settings.put(Environment.SHOW_SQL, "false");
      configuration.setProperties(settings);

      LOGGER.trace("connectionString {}", connectionString);
      // Create registry builder
      StandardServiceRegistryBuilder registryBuilder =
          new StandardServiceRegistryBuilder().applySettings(settings);
      MetadataSources metaDataSrc = new MetadataSources(registryBuilder.build());
      for (Class entity : entities) {
        metaDataSrc.addAnnotatedClass(entity);
      }

      // Check DB is up or not
      boolean dbConnectionStatus =
          checkDBConnection(
              rDBDriver, rDBUrl, databaseName, configUsername, configPassword, timeout);
      if (!dbConnectionStatus) {
        checkDBConnectionInLoop(true);
      }

      releaseLiquibaseLock(metaDataSrc);

      // Run tables liquibase migration
      createTablesLiquibaseMigration(metaDataSrc);

      // Create session factory and validate entity
      sessionFactory = metaDataSrc.buildMetadata().buildSessionFactory();

      // Export schema
      if (ModelDBConstants.EXPORT_SCHEMA) {
        exportSchema(metaDataSrc.buildMetadata());
      }

      // Check if any migration need to be run or not and based on the migration status flag
      runMigration();

      LOGGER.info(ModelDBMessages.READY_STATUS, isReady);
      isReady = true;
      return sessionFactory;
    } catch (Exception e) {
      LOGGER.warn(
          "ModelDBHibernateUtil getSessionFactory() getting error : {}", e.getMessage(), e);
      if (registry != null) {
        StandardServiceRegistryBuilder.destroy(registry);
      }
      throw new ModelDBException(e.getMessage());
    }
  } else {
    return loopBack(sessionFactory);
  }
}
 
Example 19
public static void main(String[] args) {
	try {
		Configuration cfg = new Configuration();

		boolean script = true;
		boolean drop = false;
		boolean create = false;
		boolean halt = false;
		boolean export = true;
		String outFile = null;
		String importFile = "/import.sql";
		String propFile = null;
		boolean format = false;
		String delim = null;

		for ( int i = 0; i < args.length; i++ ) {
			if ( args[i].startsWith( "--" ) ) {
				if ( args[i].equals( "--quiet" ) ) {
					script = false;
				}
				else if ( args[i].equals( "--drop" ) ) {
					drop = true;
				}
				else if ( args[i].equals( "--create" ) ) {
					create = true;
				}
				else if ( args[i].equals( "--haltonerror" ) ) {
					halt = true;
				}
				else if ( args[i].equals( "--text" ) ) {
					export = false;
				}
				else if ( args[i].startsWith( "--output=" ) ) {
					outFile = args[i].substring( 9 );
				}
				else if ( args[i].startsWith( "--import=" ) ) {
					importFile = args[i].substring( 9 );
				}
				else if ( args[i].startsWith( "--properties=" ) ) {
					propFile = args[i].substring( 13 );
				}
				else if ( args[i].equals( "--format" ) ) {
					format = true;
				}
				else if ( args[i].startsWith( "--delimiter=" ) ) {
					delim = args[i].substring( 12 );
				}
				else if ( args[i].startsWith( "--config=" ) ) {
					cfg.configure( args[i].substring( 9 ) );
				}
				else if ( args[i].startsWith( "--naming=" ) ) {
					cfg.setNamingStrategy(
							( NamingStrategy ) ReflectHelper.classForName( args[i].substring( 9 ) )
									.newInstance()
					);
				}
			}
			else {
				String filename = args[i];
				if ( filename.endsWith( ".jar" ) ) {
					cfg.addJar( new File( filename ) );
				}
				else {
					cfg.addFile( filename );
				}
			}

		}

		if ( propFile != null ) {
			Properties props = new Properties();
			props.putAll( cfg.getProperties() );
			props.load( new FileInputStream( propFile ) );
			cfg.setProperties( props );
		}

		SchemaExport se = new SchemaExport( cfg )
				.setHaltOnError( halt )
				.setOutputFile( outFile )
				.setImportFile( importFile )
				.setDelimiter( delim );
		if ( format ) {
			se.setFormat( true );
		}
		se.execute( script, export, drop, create );

	}
	catch ( Exception e ) {
		log.error( "Error creating schema ", e );
		e.printStackTrace();
	}
}
 
Example 20
public static void main(String[] args) {
	try {
		Configuration cfg = new Configuration();

		boolean script = true;
		// If true then execute db updates, otherwise just generate and display updates
		boolean doUpdate = true;
		String propFile = null;

		for ( int i = 0; i < args.length; i++ ) {
			if ( args[i].startsWith( "--" ) ) {
				if ( args[i].equals( "--quiet" ) ) {
					script = false;
				}
				else if ( args[i].startsWith( "--properties=" ) ) {
					propFile = args[i].substring( 13 );
				}
				else if ( args[i].startsWith( "--config=" ) ) {
					cfg.configure( args[i].substring( 9 ) );
				}
				else if ( args[i].startsWith( "--text" ) ) {
					doUpdate = false;
				}
				else if ( args[i].startsWith( "--naming=" ) ) {
					cfg.setNamingStrategy(
							( NamingStrategy ) ReflectHelper.classForName( args[i].substring( 9 ) ).newInstance()
					);
				}
			}
			else {
				cfg.addFile( args[i] );
			}

		}

		if ( propFile != null ) {
			Properties props = new Properties();
			props.putAll( cfg.getProperties() );
			props.load( new FileInputStream( propFile ) );
			cfg.setProperties( props );
		}

		new SchemaUpdate( cfg ).execute( script, doUpdate );
	}
	catch ( Exception e ) {
		log.error( "Error running schema update", e );
		e.printStackTrace();
	}
}