Example usage for org.hibernate.cfg Configuration buildSessionFactory

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

Introduction

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

Prototype

public SessionFactory buildSessionFactory() throws HibernateException 

Source Link

Document

Create a SessionFactory using the properties and mappings in this configuration.

Usage

From source file:com.cgi.poc.dw.dao.HibernateUtil.java

public HibernateUtil() {
    try {/*from   w w  w.j  a va2  s. c  o m*/
        File newConfiguration = new File(CONFIG_PATH);
        Yaml yaml = new Yaml();
        InputStream is = new FileInputStream(newConfiguration);

        LinkedHashMap yamlParsers = (LinkedHashMap<String, ArrayList>) yaml.load(is);

        LinkedHashMap databaseCfg = (LinkedHashMap<String, ArrayList>) yamlParsers.get("database");
        String driver = (String) databaseCfg.get("driverClass");
        String dbUrl = (String) databaseCfg.get("url");
        String userName = (String) databaseCfg.get("user");
        String userPwd = (String) databaseCfg.get("password");

        Configuration configuration = new Configuration();
        // need to be able to read config file to get the uname/pwd for testing.. can't 
        // use in memory DB b/c we need json, and geometry types which are not supported
        // by h2
        configuration.setProperty("connection.driver_class", driver);
        configuration.setProperty("hibernate.connection.url", dbUrl);
        configuration.setProperty("hibernate.connection.username", userName);
        configuration.setProperty("hibernate.connection.password", userPwd);
        configuration.setProperty("hibernate.current_session_context_class", "thread");

        configuration.addAnnotatedClass(User.class);
        configuration.addAnnotatedClass(FireEvent.class);
        configuration.addAnnotatedClass(EventEarthquake.class);
        configuration.addAnnotatedClass(EventWeather.class);
        configuration.addAnnotatedClass(EventFlood.class);
        configuration.addAnnotatedClass(EventHurricane.class);
        configuration.addAnnotatedClass(EventTsunami.class);
        configuration.addAnnotatedClass(EventVolcano.class);
        configuration.addAnnotatedClass(EventNotification.class);
        configuration.addAnnotatedClass(EventNotificationZipcode.class);
        configuration.addAnnotatedClass(EventNotificationUser.class);

        sessionFactory = configuration.buildSessionFactory();
        openSession = sessionFactory.openSession();
        Connection sqlConnection = ((SessionImpl) openSession).connection();
        sessionFactory.getCurrentSession();

        JdbcConnection conn = new JdbcConnection(sqlConnection);
        Database database = DatabaseFactory.getInstance().findCorrectDatabaseImplementation(conn);
        Liquibase liquibase = new Liquibase("migrations.xml", new ClassLoaderResourceAccessor(), database);
        String ctx = null;
        liquibase.update(ctx);
    } catch (Exception ex) {
        Logger.getLogger(HibernateUtil.class.getName()).log(Level.SEVERE, null, ex);
        System.exit(0);

    }

}

From source file:com.cloud.bridge.util.CloudSessionFactory.java

License:Open Source License

private CloudSessionFactory() {
    Configuration cfg = new Configuration();
    File file = ConfigurationHelper.findConfigurationFile("hibernate.cfg.xml");

    File propertiesFile = ConfigurationHelper.findConfigurationFile("db.properties");
    Properties dbProp = null;/*www .j av  a  2  s.  com*/
    String dbName = null;
    String dbHost = null;
    String dbUser = null;
    String dbPassword = null;
    String dbPort = null;

    if (null != propertiesFile) {

        if (EncryptionSecretKeyCheckerUtil.useEncryption()) {
            StandardPBEStringEncryptor encryptor = EncryptionSecretKeyCheckerUtil.getEncryptor();
            dbProp = new EncryptableProperties(encryptor);
        } else {
            dbProp = new Properties();
        }

        try {
            dbProp.load(new FileInputStream(propertiesFile));
        } catch (FileNotFoundException e) {
            logger.warn("Unable to open properties file: " + propertiesFile.getAbsolutePath(), e);
        } catch (IOException e) {
            logger.warn("Unable to read properties file: " + propertiesFile.getAbsolutePath(), e);
        }
    }

    //
    // we are packaging hibernate mapping files along with the class files, 
    // make sure class loader use the same class path when initializing hibernate mapping.
    // This is important when we are deploying and testing at different environment (Tomcat/JUnit test runner)
    //
    if (file != null && dbProp != null) {
        Thread.currentThread().setContextClassLoader(this.getClass().getClassLoader());
        cfg.configure(file);

        dbHost = dbProp.getProperty("db.cloud.host");
        dbName = dbProp.getProperty("db.awsapi.name");
        dbUser = dbProp.getProperty("db.cloud.username");
        dbPassword = dbProp.getProperty("db.cloud.password");
        dbPort = dbProp.getProperty("db.cloud.port");

        cfg.setProperty("hibernate.connection.url", "jdbc:mysql://" + dbHost + ":" + dbPort + "/" + dbName);
        cfg.setProperty("hibernate.connection.username", dbUser);
        cfg.setProperty("hibernate.connection.password", dbPassword);

        factory = cfg.buildSessionFactory();
    } else {
        logger.warn("Unable to open load db configuration");
        throw new RuntimeException("nable to open load db configuration");
    }
}

From source file:com.cloud.bridge.util.CloudStackSessionFactory.java

License:Open Source License

private CloudStackSessionFactory() {
    Configuration cfg = new Configuration();
    File file = ConfigurationHelper.findConfigurationFile("CloudStack.cfg.xml");

    File propertiesFile = ConfigurationHelper.findConfigurationFile("db.properties");
    Properties dbProp = null;//from w  ww.jav a2s. com
    String dbName = null;
    String dbHost = null;
    String dbUser = null;
    String dbPassword = null;
    String dbPort = null;

    if (null != propertiesFile) {

        if (EncryptionSecretKeyCheckerUtil.useEncryption()) {
            StandardPBEStringEncryptor encryptor = EncryptionSecretKeyCheckerUtil.getEncryptor();
            dbProp = new EncryptableProperties(encryptor);
        } else {
            dbProp = new Properties();
        }

        try {
            dbProp.load(new FileInputStream(propertiesFile));
        } catch (FileNotFoundException e) {
            logger.warn("Unable to open properties file: " + propertiesFile.getAbsolutePath(), e);
        } catch (IOException e) {
            logger.warn("Unable to read properties file: " + propertiesFile.getAbsolutePath(), e);
        }
    }

    //
    // we are packaging hibernate mapping files along with the class files, 
    // make sure class loader use the same class path when initializing hibernate mapping.
    // This is important when we are deploying and testing at different environment (Tomcat/JUnit test runner)
    //
    if (file != null && dbProp != null) {
        Thread.currentThread().setContextClassLoader(this.getClass().getClassLoader());
        cfg.configure(file);

        dbHost = dbProp.getProperty("db.cloud.host");
        dbName = dbProp.getProperty("db.cloud.name");
        dbUser = dbProp.getProperty("db.cloud.username");
        dbPassword = dbProp.getProperty("db.cloud.password");
        dbPort = dbProp.getProperty("db.cloud.port");

        cfg.setProperty("hibernate.connection.url", "jdbc:mysql://" + dbHost + ":" + dbPort + "/" + dbName);
        cfg.setProperty("hibernate.connection.username", dbUser);
        cfg.setProperty("hibernate.connection.password", dbPassword);

        factory = cfg.buildSessionFactory();
    } else {
        logger.warn("Unable to open load db configuration");
        throw new RuntimeException("nable to open load db configuration");
    }
}

From source file:com.cosylab.cdb.jdal.hibernate.HibernateUtil.java

License:Open Source License

/**
 * Use default configuration and add properties from Properties.
 * Build session factory from combined configuration.
 * @param config/*  www.j ava2s  .c o m*/
 */
public void setConfiguration(Properties extraProperties) {
    try {
        Configuration config = new AnnotationConfiguration();
        config.configure(getConfigurationFileName());
        config.addProperties(extraProperties);
        sessionFactory = config.buildSessionFactory();
        configuration = config;
    } catch (Throwable ex) {
        // We have to catch Throwable, otherwise we will miss
        // NoClassDefFoundError and other subclasses of Error
        logger.log(Level.SEVERE, "Building SessionFactory failed.", ex);
        throw new ExceptionInInitializerError(ex);
    }
}

From source file:com.cosylab.cdb.jdal.hibernate.HibernateUtil.java

License:Open Source License

/**
 * Set your own configuration and build session factory from it.
 * Used to tests./*  www.  j av  a2s  .c  o  m*/
 * @param config
 */
public void setConfiguration(Configuration config) {
    try {
        sessionFactory = config.buildSessionFactory();
        configuration = config;
    } catch (Throwable ex) {
        // We have to catch Throwable, otherwise we will miss
        // NoClassDefFoundError and other subclasses of Error
        logger.log(Level.SEVERE, "Building SessionFactory failed.", ex);
        throw new ExceptionInInitializerError(ex);
    }
}

From source file:com.cosylab.cdb.jdal.hibernate.HibernateUtil.java

License:Open Source License

/**
 * Rebuild the SessionFactory with the given Hibernate Configuration.
 *
 * @param cfg// w ww. j a va 2 s .co m
 */
public void rebuildSessionFactory(Configuration cfg) throws HibernateUtilException {
    synchronized (sessionFactory) {
        try {
            sessionFactory = cfg.buildSessionFactory();
            configuration = cfg;
        } catch (Exception ex) {
            throw new HibernateUtilException(ex);
        }
    }
}

From source file:com.dao.SessionUtil.java

private SessionUtil() {
    Configuration configuration = new Configuration();
    configuration.configure("hibernate.cfg.xml");

    sessionFactory = configuration.buildSessionFactory();
}

From source file:com.db4o.drs.hibernate.impl.Util.java

License:Open Source License

public static void initMySignature(Configuration cfg) {
    SessionFactory sf = cfg.buildSessionFactory();
    Session session = sf.openSession();/*ww w  .  j  a va  2 s.co m*/
    Transaction tx = session.beginTransaction();

    if (session.createCriteria(MySignature.class).list().size() < 1)
        session.save(MySignature.generateSignature());

    tx.commit();
    session.close();
    sf.close();
}

From source file:com.dz.common.dataimport2.DataImport.java

public static void init() {
        Configuration configurate = new Configuration()
                .configure(DataImport.class.getResource("apply_manage/hibernate.cfg.xml"));
        sessionFactory = configurate.buildSessionFactory();

        ctx = new ClassPathXmlApplicationContext("com/dz/common/dataimport2/applicationContext.xml");
        driverDao = ctx.getBean(DriverDao.class);
        vehicleDao = ctx.getBean(VehicleDao.class);
        contractService = ctx.getBean(ContractService.class);
        vehicleApprovalService = ctx.getBean(VehicleApprovalService.class);
    }/*from  w w w  .ja v a2 s  .c o  m*/

From source file:com.egreen.tesla.server.api.database.RepositoryConfig.java

public SessionFactory init(List<Class> classes) {

    // Create the SessionFactory from hibernate.cfg.xml
    Configuration configuration = new AnnotationConfiguration();

    configuration.setProperty("hibernate.connection.url", url);
    configuration.setProperty("hibernate.connection.username", username);
    configuration.setProperty("hibernate.connection.password", password);
    configuration.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQLDialect");
    configuration.setProperty("hibernate.connection.driver_class", JDBC_DRIVER);
    configuration.setProperty("hibernate.show_sql", "true");
    configuration.setProperty("hibernate.hbm2ddl.auto", "update");

    for (Class class1 : classes) {
        configuration = configuration.addAnnotatedClass(class1);
    }/*from   w  ww.  ja va2  s.com*/

    //ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();
    return configuration.buildSessionFactory();

}