Example usage for org.hibernate.cfg Configuration addResource

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

Introduction

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

Prototype

public Configuration addResource(String resourceName) throws MappingException 

Source Link

Document

Read mappings as a application resourceName (i.e.

Usage

From source file:edu.jhuapl.dorset.reporting.SqlReporterTest.java

License:Open Source License

@Before
public void setup() {
    Configuration conf = new Configuration();
    conf.setProperty("hibernate.connection.driver_class", "org.h2.Driver");
    conf.setProperty("hibernate.connection.url", "jdbc:h2:mem:sql_reporter");
    conf.setProperty("hibernate.connection.pool_size", "1");
    conf.setProperty("hibernate.dialect", "org.hibernate.dialect.H2Dialect");
    conf.setProperty("hibernate.hbm2ddl.auto", "create-drop");
    conf.addResource("report.hbm.xml");
    sessionFactory = conf.buildSessionFactory();
}

From source file:gov.nih.nci.security.system.ApplicationSessionFactory.java

License:Open Source License

public static SessionFactory getSessionFactory(String applicationContextName, HashMap connectionProperties)
        throws CSConfigurationException {
    SessionFactory sessionFactory = null;

    sessionFactory = (SessionFactory) appSessionFactories.get(applicationContextName);
    if (sessionFactory == null) {
        try {//from w  w  w .  j av  a2  s.c om
            Configuration configuration = new Configuration();
            configuration.addResource(
                    "gov/nih/nci/security/authorization/domainobjects/InstanceLevelMappingElement.hbm.xml");
            configuration.addResource("gov/nih/nci/security/authorization/domainobjects/Privilege.hbm.xml");
            configuration.addResource("gov/nih/nci/security/authorization/domainobjects/Application.hbm.xml");
            configuration.addResource("gov/nih/nci/security/authorization/domainobjects/FilterClause.hbm.xml");
            configuration.addResource("gov/nih/nci/security/authorization/domainobjects/Role.hbm.xml");
            configuration.addResource("gov/nih/nci/security/dao/hibernate/RolePrivilege.hbm.xml");
            configuration.addResource("gov/nih/nci/security/dao/hibernate/UserGroup.hbm.xml");
            configuration
                    .addResource("gov/nih/nci/security/dao/hibernate/ProtectionGroupProtectionElement.hbm.xml");
            configuration.addResource("gov/nih/nci/security/authorization/domainobjects/Group.hbm.xml");
            configuration.addResource("gov/nih/nci/security/authorization/domainobjects/User.hbm.xml");
            configuration
                    .addResource("gov/nih/nci/security/authorization/domainobjects/ProtectionGroup.hbm.xml");
            configuration
                    .addResource("gov/nih/nci/security/authorization/domainobjects/ProtectionElement.hbm.xml");
            configuration.addResource(
                    "gov/nih/nci/security/authorization/domainobjects/UserGroupRoleProtectionGroup.hbm.xml");
            configuration.addResource(
                    "gov/nih/nci/security/authorization/domainobjects/UserProtectionElement.hbm.xml");
            configuration.setProperty("hibernate.connection.url",
                    (String) connectionProperties.get("hibernate.connection.url"));
            configuration.setProperty("hibernate.connection.username",
                    (String) connectionProperties.get("hibernate.connection.username"));
            configuration.setProperty("hibernate.connection.password",
                    (String) connectionProperties.get("hibernate.connection.password"));
            configuration.setProperty("hibernate.dialect",
                    (String) connectionProperties.get("hibernate.dialect"));
            configuration.setProperty("hibernate.connection.driver_class",
                    (String) connectionProperties.get("hibernate.connection.driver_class"));
            configuration.setProperty("hibernate.c3p0.min_size", "5");
            configuration.setProperty("hibernate.c3p0.max_size", "20");
            configuration.setProperty("hibernate.c3p0.timeout", "300");
            configuration.setProperty("hibernate.c3p0.max_statements", "50");
            configuration.setProperty("hibernate.c3p0.idle_test_period", "3000");

            sessionFactory = configuration.buildSessionFactory();
        } catch (Exception e) {
            throw new CSConfigurationException(
                    "Error in initializing the hibernate session factory using the provided connection parameters",
                    e);
        }
        appSessionFactories.put(applicationContextName, sessionFactory);
    }
    return sessionFactory;
}

From source file:gov.nih.nci.security.upt.util.JDBCHelper.java

License:BSD License

/**
 * This method uses Hibernates SessionFactory to get a Session and using Hibernates Criteria does a sample query
 * to connection and obtain results as part of testing for successful connection.
 *
 * Based on the kind of exceptions this method throws CSException with appropriate message.
 * @param appForm -//from   w  w w .ja  v a2s  .  c o m
 *            The ApplicationForm with application database parameters to
 *            test connection for.
 * @return String - The message indicating that connection and a SQL query
 *         was successful
 * @throws CSException -
 *             The exception message indicates which kind of application
 *             database parameters are invalid.
 */
public static String testConnectionHibernate(BaseDBForm appForm) throws CSException {
    ApplicationForm appform = (ApplicationForm) appForm;

    SessionFactory sf = null;
    try {

        Configuration configuration = new Configuration();
        configuration.addResource("gov/nih/nci/security/authorization/domainobjects/Application.hbm.xml");
        configuration.setProperty("hibernate.connection.url", appform.getApplicationDatabaseURL());
        configuration.setProperty("hibernate.connection.username", appform.getApplicationDatabaseUserName());
        configuration.setProperty("hibernate.connection.password", appform.getApplicationDatabasePassword());
        configuration.setProperty("hibernate.dialect", appform.getApplicationDatabaseDialect());
        configuration.setProperty("hibernate.connection.driver_class", appform.getApplicationDatabaseDriver());
        configuration.setProperty("hibernate.connection.pool_size", "1");
        sf = configuration.buildSessionFactory();
        Session session = sf.openSession();

        Criteria criteria = session.createCriteria(ApplicationContext.class);
        criteria.add(Expression.eq("applicationName", appform.getApplicationName().trim()));
        criteria.setProjection(Projections.rowCount());

        List results = criteria.list();
        Integer integer = (Integer) results.iterator().next();
        if (integer == null) {
            session.close();
            throw new CSException(DisplayConstants.APPLICATION_DATABASE_CONNECTION_FAILED);
        }

        session.close();
        return DisplayConstants.APPLICATION_DATABASE_CONNECTION_SUCCESSFUL;

    } catch (Throwable t) {
        // Depending on the cause of the exception obtain message and throw a CSException.
        if (t instanceof SQLGrammarException) {
            throw new CSException(
                    DisplayConstants.APPLICATION_DATABASE_CONNECTION_FAILED + " " + t.getCause().getMessage());
        }
        if (t instanceof JDBCConnectionException) {
            if (t.getCause() instanceof CommunicationsException) {
                throw new CSException(DisplayConstants.APPLICATION_DATABASE_CONNECTION_FAILED_URL_SERVER_PORT);
            }
            if (t.getCause() instanceof SQLException) {
                throw new CSException(DisplayConstants.APPLICATION_DATABASE_CONNECTION_FAILED_URL);
            }
            throw new CSException(
                    DisplayConstants.APPLICATION_DATABASE_CONNECTION_FAILED + " " + t.getMessage());
        }
        if (t instanceof GenericJDBCException) {
            throw new CSException(DisplayConstants.APPLICATION_DATABASE_CONNECTION_FAILED_URL_USER_PASS);
        }
        if (t instanceof HibernateException) {
            throw new CSException(
                    DisplayConstants.APPLICATION_DATABASE_CONNECTION_FAILED + " " + t.getMessage());
        }

        throw new CSException(DisplayConstants.APPLICATION_DATABASE_CONNECTION_FAILED);
    }

}

From source file:gr.abiss.calipso.hibernate.SchemaHelper.java

License:Open Source License

/**
 * create tables using the given Hibernate configuration
 *//*w w w.ja v  a 2  s  .com*/
public void updateSchema() {
    Configuration cfg = new Configuration();
    if (StringUtils.hasText(dataSourceJndiName)) {
        cfg.setProperty("hibernate.connection.datasource", dataSourceJndiName);
    } else {
        cfg.setProperty("hibernate.connection.driver_class", driverClassName);
        cfg.setProperty("hibernate.connection.url", url);
        cfg.setProperty("hibernate.connection.username", username);
        cfg.setProperty("hibernate.connection.password", password);
    }
    cfg.setProperty("hibernate.dialect", hibernateDialect);
    for (String resource : mappingResources) {
        cfg.addResource(resource);
    }
    logger.info("begin database schema creation =========================");
    new SchemaUpdate(cfg).execute(true, true);
    logger.info("end database schema creation ===========================");
}

From source file:gr.interamerican.bo2.impl.open.hibernate.HibernateConfigurations.java

License:Open Source License

/**
 * Creates a SessionFactory.//from   ww  w.  ja  va  2  s.co m
 * 
 * @param pathToCfg
 *        Path to the hibernate configuration file.
 * @param dbSchema
 *        Db schema.
 * @param sessionInterceptor
 *        Hibernate session interceptor.
 * @param hibernateMappingsPath
 *        Path to file that lists files indexing hbm files this session factory
 *        should be configured with
 * 
 * @return Returns the session factory.
 * 
 * @throws InitializationException
 *         If the creation of the SessionFactory fails.
 */
@SuppressWarnings("nls")
static SessionFactory createSessionFactory(String pathToCfg, String dbSchema, String sessionInterceptor,
        String hibernateMappingsPath) throws InitializationException {
    try {
        Configuration conf = new Configuration();

        Interceptor interceptor = getInterceptor(sessionInterceptor);
        if (interceptor != null) {
            conf.setInterceptor(interceptor);
        }

        conf.setProperty(SCHEMA_PROPERTY, dbSchema);

        List<String> hbms = getHibernateMappingsIfAvailable(hibernateMappingsPath);
        for (String entityMapping : hbms) {
            LOGGER.debug("Adding " + entityMapping + " to the session factory configuration.");
            conf.addResource(entityMapping);
        }

        conf.configure(pathToCfg);

        conf.getEntityTuplizerFactory().registerDefaultTuplizerClass(EntityMode.POJO,
                Bo2PojoEntityTuplizer.class);
        SessionFactory sessionFactory = conf.buildSessionFactory();
        ((SessionFactoryImpl) sessionFactory).registerEntityNameResolver(Bo2EntityNameResolver.INSTANCE,
                EntityMode.POJO);
        sessionFactory.getStatistics().setStatisticsEnabled(true);
        return sessionFactory;
    } catch (HibernateException e) {
        throw new InitializationException(e);
    }
}

From source file:griffon.plugins.hibernate3.internal.HibernateConfigurationHelper.java

License:Apache License

private void applyMappings(final Configuration config) {
    try {/*ww  w  .  j ava2  s.c o m*/
        Enumeration<URL> urls = getClass().getClassLoader().getResources("META-INF/hibernate3/mappings.txt");
        while (urls.hasMoreElements()) {
            eachLine(urls.nextElement(), new RunnableWithArgsClosure(new RunnableWithArgs() {
                @Override
                public void run(Object[] args) {
                    String line = ((String) args[0]).trim();
                    if (isBlank(line))
                        return;
                    config.addResource(line);
                }
            }));
        }
    } catch (IOException e) {
        throw new IllegalArgumentException(e);
    }
}

From source file:griffon.plugins.hibernate4.internal.HibernateConfigurationHelper.java

License:Apache License

private void applyMappings(final Configuration config) {
    try {//from  w  w  w.ja  v  a  2 s. c  o m
        Enumeration<URL> urls = getClass().getClassLoader().getResources("META-INF/hibernate4/mappings.txt");
        while (urls.hasMoreElements()) {
            eachLine(urls.nextElement(), new RunnableWithArgsClosure(new RunnableWithArgs() {
                @Override
                public void run(Object[] args) {
                    String line = ((String) args[0]).trim();
                    if (isBlank(line))
                        return;
                    config.addResource(line);
                }
            }));
        }
    } catch (IOException e) {
        throw new IllegalArgumentException(e);
    }
}

From source file:info.jtrac.hibernate.SchemaHelper.java

License:Apache License

/**
 * Create tables using the given Hibernate configuration data.
 *///from   w ww  .jav a  2 s  . c om
public void createSchema() {
    Configuration cfg = new Configuration();

    if (StringUtils.hasText(dataSourceJndiName)) {
        cfg.setProperty("hibernate.connection.datasource", dataSourceJndiName);
    } else {
        cfg.setProperty("hibernate.connection.driver_class", driverClassName);
        cfg.setProperty("hibernate.connection.url", url);
        cfg.setProperty("hibernate.connection.username", username);
        cfg.setProperty("hibernate.connection.password", password);
    } // end if..else

    cfg.setProperty("hibernate.dialect", hibernateDialect);

    for (String resource : mappingResources) {
        cfg.addResource(resource);
    } // end for

    logger.info("begin database schema creation =========================");
    new SchemaUpdate(cfg).execute(true, true);
    logger.info("end database schema creation ===========================");
}

From source file:main.java.info.jtrac.hibernate.SchemaHelper.java

License:Apache License

/**
 * create tables using the given Hibernate configuration
 *//*from  w w w  .  j  a va 2 s  .c o  m*/
public void createSchema() {
    Configuration cfg = new Configuration();
    if (StringUtils.hasText(dataSourceJndiName)) {
        cfg.setProperty("hibernate.connection.datasource", dataSourceJndiName);
    } else {
        cfg.setProperty("hibernate.connection.driver_class", driverClassName);
        cfg.setProperty("hibernate.connection.url", url);
        cfg.setProperty("hibernate.connection.username", username);
        cfg.setProperty("hibernate.connection.password", password);
    }
    cfg.setProperty("hibernate.dialect", hibernateDialect);
    for (String resource : mappingResources) {
        cfg.addResource(resource);
    }
    logger.info("begin database schema creation =========================");
    new SchemaUpdate(cfg).execute(true, true);
    logger.info("end database schema creation ===========================");
}

From source file:myrmidia.Database.Connector.java

License:Open Source License

/**
 * This mehtod is used to override a hard-coded parameter in the
 * hibernate.cfg.xml file to give a the application a limited altered
 * configuration. Used to permit hibernate to create non-existing tables.
 * @param file URL the url path to the hibernate.cfg.xml file
 * @throws InitializingException//  w ww. jav  a  2 s .  c  om
 */
public void initOverwriteFromXMLFile(URL file) throws InitializingException {
    try {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document document = builder.parse(file.openStream());

        String hcf = document.getElementsByTagName("HibernateConfigFile").item(0).getTextContent();

        String descriptionMapFile = document.getElementsByTagName("DescriptionMappingFile").item(0)
                .getTextContent();
        descriptionClassName = document.getElementsByTagName("DescriptionClassName").item(0).getTextContent();

        Configuration hbconfig = new Configuration();
        hbconfig.configure(FileIO.findFile(hcf));
        hbconfig.addURL(FileIO.findFile(descriptionMapFile));

        try {
            String solutionMapFile = document.getElementsByTagName("SolutionMappingFile").item(0)
                    .getTextContent();
            solutionClassName = document.getElementsByTagName("SolutionClassName").item(0).getTextContent();
            hbconfig.addResource(solutionMapFile);
        } catch (Exception e) {
            LogFactory.getLog(this.getClass()).info("Case does not have solution");
        }

        try {
            String justOfSolutionMapFile = document.getElementsByTagName("JustificationOfSolutionMappingFile")
                    .item(0).getTextContent();
            justOfSolutionClassName = document.getElementsByTagName("JustificationOfSolutionClassName").item(0)
                    .getTextContent();
            hbconfig.addResource(justOfSolutionMapFile);
        } catch (Exception e) {
            LogFactory.getLog(this.getClass()).info("Case does not have justification of the solution");
        }

        try {
            String resultMapFile = document.getElementsByTagName("ResultMappingFile").item(0).getTextContent();
            resultClassName = document.getElementsByTagName("ResultClassName").item(0).getTextContent();
            hbconfig.addResource(resultMapFile);
        } catch (Exception e) {
            LogFactory.getLog(this.getClass()).info("Case does not have result");
        }
        hbconfig.setProperty("hibernate.hbm2ddl.auto", "update");
        String currentProperty = hbconfig.getProperty("hibernate.connection.url");
        currentProperty += ";create=true";
        hbconfig.setProperty("hibernate.connection.url", currentProperty);
        sessionFactory = hbconfig.buildSessionFactory();
    } catch (Throwable ex) {
        throw new InitializingException(ex);
    }
}