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

The following examples show how to use org.hibernate.cfg.Configuration#configure() . 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: CRUDTest.java    From Project with Apache License 2.0 6 votes vote down vote up
@Test
public void deleteTest(){
    Configuration configuration = new Configuration();
    configuration.configure();

    SessionFactory sessionFactory = configuration.buildSessionFactory();
    Session session = sessionFactory.openSession();

    Transaction transaction = session.beginTransaction();

    User user = session.get(User.class, 1);
    session.delete(user);

    transaction.commit();

    session.close();
    sessionFactory.close();
}
 
Example 2
Source File: HibernateUtil.java    From tutorials with MIT License 6 votes vote down vote up
private static SessionFactory buildSessionFactory() {
    try {
        // Create the SessionFactory from hibernate-annotation.cfg.xml
        Configuration configuration = new Configuration();
        configuration.addAnnotatedClass(Employee.class);
        configuration.addAnnotatedClass(Project.class);
        configuration.configure("manytomany.cfg.xml");
        System.out.println("Hibernate Annotation Configuration loaded");

        ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties())
            .build();
        System.out.println("Hibernate Annotation serviceRegistry created");

        SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry);

        return sessionFactory;
    } catch (Throwable ex) {
        System.err.println("Initial SessionFactory creation failed." + ex);
        ex.printStackTrace();
        throw new ExceptionInInitializerError(ex);
    }
}
 
Example 3
Source File: HibernateUtil.java    From lambda-rds-mysql with Apache License 2.0 6 votes vote down vote up
public static SessionFactory getSessionFactory() {
    if (null != sessionFactory)
        return sessionFactory;
    
    Configuration configuration = new Configuration();

    String jdbcUrl = "jdbc:mysql://"
            + System.getenv("RDS_HOSTNAME")
            + "/"
            + System.getenv("RDS_DB_NAME");
    
    configuration.setProperty("hibernate.connection.url", jdbcUrl);
    configuration.setProperty("hibernate.connection.username", System.getenv("RDS_USERNAME"));
    configuration.setProperty("hibernate.connection.password", System.getenv("RDS_PASSWORD"));

    configuration.configure();
    ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
    try {
        sessionFactory = configuration.buildSessionFactory(serviceRegistry);
    } catch (HibernateException e) {
        System.err.println("Initial SessionFactory creation failed." + e);
        throw new ExceptionInInitializerError(e);
    }
    return sessionFactory;
}
 
Example 4
Source File: HibernateUtil.java    From journaldev with MIT License 6 votes vote down vote up
private static SessionFactory buildSessionFactory() {
    try {
        // Create the SessionFactory from hibernate.cfg.xml
    	Configuration configuration = new Configuration();
    	configuration.configure("hibernate.cfg.xml");
    	System.out.println("Hibernate Configuration loaded");
    	
    	ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
    	System.out.println("Hibernate serviceRegistry created");
    	
    	SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry);
    	
        return sessionFactory;
    }
    catch (Throwable ex) {
        // Make sure you log the exception, as it might be swallowed
        System.err.println("Initial SessionFactory creation failed." + ex);
        throw new ExceptionInInitializerError(ex);
    }
}
 
Example 5
Source File: SchemaValidatorTask.java    From cacheonix-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
private Configuration getConfiguration() throws Exception {
	Configuration cfg = new Configuration();
	if (namingStrategy!=null) {
		cfg.setNamingStrategy(
				(NamingStrategy) ReflectHelper.classForName(namingStrategy).newInstance()
			);
	}
	if (configurationFile!=null) {
		cfg.configure( configurationFile );
	}

	String[] files = getFiles();
	for (int i = 0; i < files.length; i++) {
		String filename = files[i];
		if ( filename.endsWith(".jar") ) {
			cfg.addJar( new File(filename) );
		}
		else {
			cfg.addFile(filename);
		}
	}
	return cfg;
}
 
Example 6
Source File: OneToOneMappingExample.java    From Examples with MIT License 6 votes vote down vote up
public static void main(String[] args) {
    try {
        /* Create hibernate configuration. */
        Configuration configuration = new Configuration();
        configuration.configure("com\\javaquery\\database\\hibernate\\hibernate.cfg.xml");

        /* Open session and begin database transaction for database operation. */
        SessionFactory sessionFactory = configuration.buildSessionFactory();
        Session session = sessionFactory.openSession();
        
        Country country = session.load(Country.class, 1L);
        System.out.println(country);
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example 7
Source File: CRUDTest.java    From Project with Apache License 2.0 6 votes vote down vote up
@Test
public void selectTest(){
    Configuration configuration = new Configuration();
    configuration.configure();

    SessionFactory sessionFactory = configuration.buildSessionFactory();
    Session session = sessionFactory.openSession();

    Transaction transaction = session.beginTransaction();

    User user = session.get(User.class, 1);
    System.out.println(user);

    transaction.commit();

    session.close();
    sessionFactory.close();
}
 
Example 8
Source File: HibernateUtil.java    From collect-earth with MIT License 6 votes vote down vote up
private static SessionFactory buildSessionFactory() {
    try {
        // Create the SessionFactory from hibernate.cfg.xml
    	Configuration configuration = new Configuration();
    	configuration.configure("hibernate.cfg.xml");
    	System.out.println("Hibernate Configuration loaded");
    	
    	configuration.addAnnotatedClass(Plot.class); 
    	
    	ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
    	System.out.println("Hibernate serviceRegistry created");
    	
    	SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry);
 
        return sessionFactory;
    }
    catch (Throwable ex) {
        System.err.println("Initial SessionFactory creation failed." + ex);
        ex.printStackTrace();
        throw new ExceptionInInitializerError(ex);
    }
}
 
Example 9
Source File: SchemaUpdateTask.java    From cacheonix-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
private Configuration getConfiguration() throws Exception {
	Configuration cfg = new Configuration();
	if (namingStrategy!=null) {
		cfg.setNamingStrategy(
				(NamingStrategy) ReflectHelper.classForName(namingStrategy).newInstance()
			);
	}
	if (configurationFile!=null) {
		cfg.configure( configurationFile );
	}

	String[] files = getFiles();
	for (int i = 0; i < files.length; i++) {
		String filename = files[i];
		if ( filename.endsWith(".jar") ) {
			cfg.addJar( new File(filename) );
		}
		else {
			cfg.addFile(filename);
		}
	}
	return cfg;
}
 
Example 10
Source File: HibernateAnnotationUtil.java    From journaldev with MIT License 6 votes vote down vote up
private static SessionFactory buildSessionFactory() {
    try {
        // Create the SessionFactory from hibernate-annotation.cfg.xml
    	Configuration configuration = new Configuration();
    	configuration.configure("hibernate-annotation.cfg.xml");
    	System.out.println("Hibernate Annotation Configuration loaded");
    	
    	ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
    	System.out.println("Hibernate Annotation serviceRegistry created");
    	
    	SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry);
    	
        return sessionFactory;
    }
    catch (Throwable ex) {
        System.err.println("Initial SessionFactory creation failed." + ex);
        ex.printStackTrace();
        throw new ExceptionInInitializerError(ex);
    }
}
 
Example 11
Source File: OneToManyMappingExample.java    From Examples with MIT License 6 votes vote down vote up
public static void main(String[] args) {
    try {
        /* Create hibernate configuration. */
        Configuration configuration = new Configuration();
        configuration.configure("com\\javaquery\\database\\hibernate\\hibernate.cfg.xml");

        /* Open session and begin database transaction for database operation. */
        SessionFactory sessionFactory = configuration.buildSessionFactory();
        Session session = sessionFactory.openSession();

        Country country = session.load(Country.class, 1L);
        if(!country.getStates().isEmpty()){
            for (State state: country.getStates()) {
                System.out.println(state.getName());
            }
        }else{
            System.out.println("No states found!");
        }
        
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example 12
Source File: HibernateSessionFactoryListener.java    From journaldev with MIT License 5 votes vote down vote up
public void contextInitialized(ServletContextEvent servletContextEvent) {
	Configuration configuration = new Configuration();
	configuration.configure("hibernate.cfg.xml");
	logger.info("Hibernate Configuration created successfully");
	
	ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
	logger.info("ServiceRegistry created successfully");
	SessionFactory sessionFactory = configuration
.buildSessionFactory(serviceRegistry);
	logger.info("SessionFactory created successfully");
	
	servletContextEvent.getServletContext().setAttribute("SessionFactory", sessionFactory);
	logger.info("Hibernate SessionFactory Configured successfully");
}
 
Example 13
Source File: StartupDataLoader.java    From maven-framework-project with MIT License 5 votes vote down vote up
/**
 * Constructing a new Hibernate SessionFactory for every request would cause very poor performance.  However, 
 * Java servlets must be thread-safe, so we can't use a SessionFactory as an instance variable.  This method provides 
 * thread-safe access to a SessionFactory, so the startup data loader and the search servlet can open Hibernate sessions 
 * more efficiently.
 * 
 * @return Session
 */
public static synchronized Session openSession() {
	if(sessionFactory == null) {
		Configuration configuration = new Configuration();
		configuration.configure();
		ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();
		sessionFactory = configuration.buildSessionFactory(serviceRegistry);			
	}
	return sessionFactory.openSession();
}
 
Example 14
Source File: RMDBManager.java    From scheduling with GNU Affero General Public License v3.0 5 votes vote down vote up
private static RMDBManager createUsingProperties() {
    if (System.getProperty(RM_DATABASE_IN_MEMORY) != null) {
        return createInMemoryRMDBManager();
    } else {
        File configFile = new File(PAResourceManagerProperties.getAbsolutePath(PAResourceManagerProperties.RM_DB_HIBERNATE_CONFIG.getValueAsString()));

        boolean drop = PAResourceManagerProperties.RM_DB_HIBERNATE_DROPDB.getValueAsBoolean();
        boolean dropNS = PAResourceManagerProperties.RM_DB_HIBERNATE_DROPDB_NODESOURCES.getValueAsBoolean();

        if (logger.isInfoEnabled()) {
            logger.info("Starting RM DB Manager " + "with drop DB = " + drop + " and drop nodesources = " + dropNS +
                        " and configuration file = " + configFile.getAbsolutePath());
        }

        Configuration configuration = new Configuration();

        if (configFile.getName().endsWith(".xml")) {
            configuration.configure(configFile);
        } else {
            try {
                Properties properties = PropertyDecrypter.getDecryptableProperties();
                properties.load(Files.newBufferedReader(configFile.toPath(), Charset.defaultCharset()));
                configuration.addProperties(properties);
                // Unwrap the decrypted property to let the connection pool framework see it
                // (as the connection pool framework reads properties using entryset iterators and jasypt EncryptableProperties does not override them)
                configuration.setProperty(PROP_HIBERNATE_CONNECTION_PASSWORD,
                                          properties.getProperty(PROP_HIBERNATE_CONNECTION_PASSWORD));
            } catch (IOException e) {
                throw new IllegalArgumentException(e);
            }
        }

        return new RMDBManager(configuration, drop, dropNS);
    }
}
 
Example 15
Source File: SessionBox.java    From oim-fx with MIT License 5 votes vote down vote up
private void load(String url) {
	File configFile = new File(SessionBox.class.getResource("/config/hibernate/hibernate.cfg.xml").getPath());
	Configuration configuration = new Configuration();
	configuration.configure(configFile);
	configuration.setProperty("hibernate.connection.url", url);
	configuration.setProperty("hibernate.connection.username", "oim");
	configuration.setProperty("hibernate.connection.password", "[email protected]");
	// configuration.setProperty("hibernate.connection.driver_class","org.h2.Driver");
	// configuration.setProperty("hibernate.dialect","org.hibernate.dialect.H2Dialect");
	//
	// configuration.setProperty("hibernate.show_sql","false");
	// configuration.setProperty("hibernate.hbm2ddl.auto","update");
	// configuration.setProperty("hibernate.query.substitutions","true 1,
	// false 0");
	// configuration.setProperty("hibernate.jdbc.fetch_size","50");
	// configuration.setProperty("hibernate.jdbc.batch_size","50");
	// configuration.setProperty("hibernate.transaction.coordinator_class","jdbc");
	// configuration.setProperty("hibernate.cache.region.factory_class","org.hibernate.cache.ehcache.EhCacheRegionFactory");
	// configuration.setProperty("hibernate.cache.use_second_level_cache","false");
	// configuration.setProperty("hibernate.cache.use_query_cache","true");
	// configuration.setProperty("hibernate.cache.provider_configuration_file_resource_path","ehcache.xml");
	// configuration.setProperty("hibernate.search.default.directory_provider","org.hibernate.search.store.impl.FSDirectoryProvider");
	try {
		sessionFactory = configuration.buildSessionFactory();
	} catch (Exception e) {
		e.printStackTrace();
	}
}
 
Example 16
Source File: StartupDataLoader.java    From maven-framework-project with MIT License 5 votes vote down vote up
/**
 * Constructing a new Hibernate SessionFactory for every request would cause very poor performance.  However, 
 * Java servlets must be thread-safe, so we can't use a SessionFactory as an instance variable.  This method provides 
 * thread-safe access to a SessionFactory, so the startup data loader and the search servlet can open Hibernate sessions 
 * more efficiently.
 * 
 * @return Session
 */
public static synchronized Session openSession() {
	if(sessionFactory == null) {
		Configuration configuration = new Configuration();
		configuration.configure();
		ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();
		sessionFactory = configuration.buildSessionFactory(serviceRegistry);			
	}
	return sessionFactory.openSession();
}
 
Example 17
Source File: AccountSummaryDAO.java    From primefaces-blueprints with The Unlicense 5 votes vote down vote up
private  SessionFactory configureSessionFactory()
		throws HibernateException {
	Configuration configuration = new Configuration();
	configuration.configure();
	StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder()
			.applySettings(configuration.getProperties());
	SessionFactory sessionfactory = configuration
			.buildSessionFactory(builder.build());
	return sessionfactory;
}
 
Example 18
Source File: CacheTest.java    From Project with Apache License 2.0 4 votes vote down vote up
@Test
public void checkCache(){
    Configuration configuration = new Configuration();
    configuration.configure();

    SessionFactory sessionFactory = configuration.buildSessionFactory();
    Session session = sessionFactory.openSession();

    Transaction transaction = session.beginTransaction();

    User user1 = session.get(User.class, 2);
    System.out.println(user1);

    User user2 = session.get(User.class, 2);
    System.out.println(user2);

    System.out.println(user1.equals(user2));


    transaction.commit();

    session.close();
    sessionFactory.close();

}
 
Example 19
Source File: HibernateTest.java    From mybatis-test with Apache License 2.0 4 votes vote down vote up
@Before
public void init() {
    Configuration configuration = new Configuration();
    configuration.configure("chapter1/hibernate.cfg.xml");
    buildSessionFactory = configuration.buildSessionFactory();
}
 
Example 20
Source File: HibernateInheritanceSingleTable.java    From java-course-ee with MIT License 4 votes vote down vote up
private static void init() {
    Configuration configuration = new Configuration();
    configuration.configure("hibernate.cfg.xml");
    serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
    sessionFactory = configuration.buildSessionFactory(serviceRegistry);
}