Example usage for org.hibernate.cfg Configuration getProperty

List of usage examples for org.hibernate.cfg Configuration getProperty

Introduction

In this page you can find the example usage for org.hibernate.cfg Configuration getProperty.

Prototype

public String getProperty(String propertyName) 

Source Link

Document

Get a property value by name

Usage

From source file:org.springframework.orm.hibernate3.LocalSessionFactoryBeanTests.java

License:Apache License

@Test
@SuppressWarnings("serial")
public void testLocalSessionFactoryBeanWithDataSourceAndMappingResources() throws Exception {
    final DriverManagerDataSource ds = new DriverManagerDataSource();
    final TransactionManager tm = mock(TransactionManager.class);
    final List invocations = new ArrayList();
    LocalSessionFactoryBean sfb = new LocalSessionFactoryBean() {
        @Override/* w  w  w .ja  va  2s.  c  o m*/
        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(LocalJtaDataSourceConnectionProvider.class.getName(),
                    config.getProperty(Environment.CONNECTION_PROVIDER));
            assertEquals(ds, LocalSessionFactoryBean.getConfigTimeDataSource());
            assertEquals(LocalTransactionManagerLookup.class.getName(),
                    config.getProperty(Environment.TRANSACTION_MANAGER_STRATEGY));
            assertEquals(tm, LocalSessionFactoryBean.getConfigTimeTransactionManager());
            invocations.add("newSessionFactory");
            return null;
        }
    };
    sfb.setMappingResources(new String[] { "/org/springframework/beans/factory/xml/test.xml",
            "/org/springframework/beans/factory/xml/child.xml" });
    sfb.setDataSource(ds);
    sfb.setJtaTransactionManager(tm);
    sfb.afterPropertiesSet();
    assertTrue(sfb.getConfiguration() != null);
    assertEquals("addResource", invocations.get(0));
    assertEquals("addResource", invocations.get(1));
    assertEquals("newSessionFactory", invocations.get(2));
}

From source file:org.springframework.orm.hibernate3.LocalSessionFactoryBeanTests.java

License:Apache License

@Test
@SuppressWarnings("serial")
public void testLocalSessionFactoryBeanWithDataSourceAndMappingJarLocations() throws Exception {
    final DriverManagerDataSource ds = new DriverManagerDataSource();
    final Set invocations = new HashSet();
    LocalSessionFactoryBean sfb = new LocalSessionFactoryBean() {
        @Override/*from  w w  w.ja  v a 2s.co m*/
        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"));
}

From source file:org.springframework.orm.hibernate3.LocalSessionFactoryBeanTests.java

License:Apache License

@Test
@SuppressWarnings("serial")
public void testLocalSessionFactoryBeanWithDataSourceAndProperties() throws Exception {
    final DriverManagerDataSource ds = new DriverManagerDataSource();
    final Set invocations = new HashSet();
    LocalSessionFactoryBean sfb = new LocalSessionFactoryBean() {
        @Override//ww w.j  av  a2 s . c  o  m
        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(LocalDataSourceConnectionProvider.class.getName(),
                    config.getProperty(Environment.CONNECTION_PROVIDER));
            assertEquals(ds, LocalSessionFactoryBean.getConfigTimeDataSource());
            assertEquals("myValue", config.getProperty("myProperty"));
            invocations.add("newSessionFactory");
            return null;
        }
    };
    sfb.setMappingLocations(
            new Resource[] { new ClassPathResource("/org/springframework/beans/factory/xml/test.xml") });
    sfb.setDataSource(ds);
    Properties prop = new Properties();
    prop.setProperty(Environment.CONNECTION_PROVIDER, "myClass");
    prop.setProperty("myProperty", "myValue");
    sfb.setHibernateProperties(prop);
    sfb.afterPropertiesSet();
    assertTrue(sfb.getConfiguration() != null);
    assertTrue(invocations.contains("addResource"));
    assertTrue(invocations.contains("newSessionFactory"));
}

From source file:org.springframework.orm.hibernate3.LocalSessionFactoryBeanTests.java

License:Apache License

@Test
public void testLocalSessionFactoryBeanWithValidProperties() throws Exception {
    final Set invocations = new HashSet();
    LocalSessionFactoryBean sfb = new LocalSessionFactoryBean() {
        @Override/*from  w w w .ja va 2s.c om*/
        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"));
}

From source file:org.squashtest.tm.service.internal.hibernate.SquashEntityManagerFactoryBuilderImpl.java

License:Open Source License

protected Configuration extendConfiguration(Configuration conf) {
    String dialect = conf.getProperty("hibernate.dialect");

    SessionFactoryEnhancer.registerExtensions(conf, configureFunctionSupport(dialect));

    conf.setNamingStrategy(new UppercaseUnderscoreNamingStrategy());
    conf.setInterceptor(new AuditLogInterceptor());

    return conf;//from  w w w .  j a  va  2 s.  co m
}

From source file:org.transitime.db.hibernate.HibernateUtils.java

License:Open Source License

/**
 * Creates a new session factory. This is to be cached and only access
 * internally since creating one is expensive.
 * /*  w  w w .j  a  v a 2  s  .c o  m*/
 * @param dbName
 * @return
 */
private static SessionFactory createSessionFactory(String dbName) throws HibernateException {
    logger.debug("Creating new Hibernate SessionFactory for dbName={}", dbName);

    // Create a Hibernate configuration based on customized config file
    Configuration config = new Configuration();

    // Want to be able to specify a configuration file for now
    // since developing in Eclipse and want all config files
    // to be in same place. But the Config.configure(String) 
    // method can't seem to work with a Windows directory name such
    // as C:/users/Mike/software/hibernate.cfg.xml . Therefore create
    // a File object for that file name and pass in the File object
    // to configure().
    String fileName = DbSetupConfig.getHibernateConfigFileName();
    logger.info("Configuring Hibernate for dbName={} using config file={}", dbName, fileName);
    File f = new File(fileName);
    if (!f.exists()) {
        logger.info(
                "The Hibernate file {} doesn't exist as a regular file " + "so seeing if it is in classpath.",
                fileName);

        // Couldn't find file directly so look in classpath for it
        ClassLoader classLoader = HibernateUtils.class.getClassLoader();
        URL url = classLoader.getResource(fileName);
        if (url != null)
            f = new File(url.getFile());
    }
    if (f.exists())
        config.configure(f);
    else {
        logger.error("Could not load in hibernate config file {}", fileName);
    }

    // Add the annotated classes so that they can be used
    AnnotatedClassesList.addAnnotatedClasses(config);

    // Set the db info for the URL, user name, and password. Use values 
    // from CoreConfig if set. If they are not set then the values will be 
    // obtained from the hibernate.cfg.xml 
    // config file.
    String dbUrl = null;
    if (DbSetupConfig.getDbHost() != null) {
        dbUrl = "jdbc:" + DbSetupConfig.getDbType() + "://" + DbSetupConfig.getDbHost() + "/" + dbName;
        config.setProperty("hibernate.connection.url", dbUrl);
    } else {
        dbUrl = config.getProperty("hibernate.connection.url");
    }

    String dbUserName = DbSetupConfig.getDbUserName();
    if (dbUserName != null) {
        config.setProperty("hibernate.connection.username", dbUserName);
    } else {
        dbUserName = config.getProperty("hibernate.connection.username");
    }

    if (DbSetupConfig.getDbPassword() != null)
        config.setProperty("hibernate.connection.password", DbSetupConfig.getDbPassword());

    // Log info, but don't log password. This can just be debug logging
    // even though it is important because the C3P0 connector logs the info.
    logger.debug(
            "For Hibernate factory project dbName={} " + "using url={} username={}, and configured password",
            dbName, dbUrl, dbUserName);

    // Get the session factory for persistence
    Properties properties = config.getProperties();
    ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(properties).build();
    SessionFactory sessionFactory = config.buildSessionFactory(serviceRegistry);

    // Return the factory
    return sessionFactory;
}

From source file:org.unitils.orm.hibernate.HibernateModule.java

License:Apache License

/**
 * Gets the database dialect from the given Hibernate <code>Configuration</code.
 *
 * @param configuration The hibernate config, not null
 * @return the database Dialect, not null
 *///  w  w w . j  a  v  a2s . c o m
protected Dialect getDatabaseDialect(Configuration configuration) {
    String dialectClassName = configuration.getProperty("hibernate.dialect");
    if (isEmpty(dialectClassName)) {
        throw new UnitilsException("Property hibernate.dialect not specified");
    }
    try {
        return (Dialect) Class.forName(dialectClassName).newInstance();
    } catch (Exception e) {
        throw new UnitilsException("Could not instantiate dialect class " + dialectClassName, e);
    }
}

From source file:org.unitils.orm.hibernate.HibernateModuleConfigurationInheritanceTest.java

License:Apache License

/**
 * Tests loading of a configuration location specified on class-level.
 * Both super and sub class have annotations with values and custom create methods.
 *///from   w  ww  .  j a  v  a  2  s .  com
@Test
public void testGetHibernateConfiguration_overriden() {
    HibernateTestCustomInit hibernateTest1 = new HibernateTestCustomInit();
    Configuration hibernateConfiguration = hibernateModule.getConfigurationObject(hibernateTest1);

    assertNotNull(hibernateConfiguration);
    assertEquals("org/unitils/orm/hibernate/hibernate-sub.cfg.xml", hibernateConfiguration.getProperty("name"));
    assertFalse(hibernateTest1.initMethod1Called);
    assertTrue(hibernateTest1.initMethod2Called);
}

From source file:org.unitils.orm.hibernate.HibernateModuleConfigurationInheritanceTest.java

License:Apache License

/**
 * Tests loading of a configuration location specified on class-level.
 * Both super and sub class have annotations with values and but only super class has custom create method.
 *//* w  ww .jav a 2 s  .  c o  m*/
@Test
public void testGetHibernateConfiguration_overridenNoCustomCreateInSubClass() {
    HibernateTestNoCustomCreate hibernateTest2 = new HibernateTestNoCustomCreate();
    Configuration hibernateConfiguration = hibernateModule.getConfigurationObject(hibernateTest2);

    assertNotNull(hibernateConfiguration);
    assertEquals("org/unitils/orm/hibernate/hibernate-sub.cfg.xml", hibernateConfiguration.getProperty("name"));
    assertFalse(hibernateTest2.initMethod1Called);
}

From source file:org.unitils.orm.hibernate.HibernateModuleConfigurationInheritanceTest.java

License:Apache License

/**
 * Tests creating the application context. No context creation is done in the sub-class, the context of the super
 * class should be used.//  ww w .  j a va 2 s. c  o  m
 */
@Test
public void testGetHibernateConfiguration_onlyInSuperClass() {
    HibernateTestNoCreation1 hibernateTestNoCreation = new HibernateTestNoCreation1();
    Configuration hibernateConfiguration = hibernateModule.getConfigurationObject(hibernateTestNoCreation);

    assertNotNull(hibernateConfiguration);
    assertEquals("org/unitils/orm/hibernate/hibernate.cfg.xml", hibernateConfiguration.getProperty("name"));
    assertTrue(hibernateTestNoCreation.initMethod1Called);
}