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.mypkg.repository.repoimpl.EmployeeRepositoryImplementation.java

@Override
public void deleteEmployee(int id) {
    //  String sql = "DELETE FROM employee WHERE id=?";
    //jdbc.update(sql, id);
    Configuration cf = new Configuration();
    cf.configure("hibernate.cfg.xml");

    SessionFactory sf = cf.buildSessionFactory();
    Session hsession = sf.openSession();
    Transaction tx = hsession.beginTransaction();
    String hql = "DELETE from Employee where id=:emp_id";
    Query q = hsession.createQuery(hql);
    q.setParameter("emp_id", id);
    int result = q.executeUpdate();

    if (result == 1) {
        tx.commit();/*from  w  w  w.  ja  v a 2s  .c  o  m*/
    } else {
        tx.rollback();
    }
}

From source file:com.mypkg.repository.repoimpl.EmployeeRepositoryImplementation.java

@Override
public void addEmployee(int id, String emp_name, int dept_id) {
    Configuration cf = new Configuration();
    cf.configure("hibernate.cfg.xml");

    SessionFactory sf = cf.buildSessionFactory();
    Session hsession = sf.openSession();
    Transaction tx = hsession.beginTransaction();
    Query query = hsession.createSQLQuery("INSERT INTO EMPLOYEE VALUES (:id,:ename,:deptid)");
    query.setInteger("id", id);
    query.setString("ename", emp_name);
    query.setInteger("deptid", dept_id);
    query.executeUpdate();/*from  w w w .  java2  s  . c  o m*/
    tx.commit();

}

From source file:com.mysema.testutil.HibernateTestRunner.java

License:Apache License

private void start() throws Exception {
    Configuration cfg = new Configuration();
    for (Class<?> cl : Domain.classes) {
        cfg.addAnnotatedClass(cl);/*from  w ww .  ja va2 s. co  m*/
    }
    String mode = Mode.mode.get() + ".properties";
    isDerby = mode.contains("derby");
    if (isDerby) {
        Class.forName("org.apache.derby.jdbc.EmbeddedDriver").newInstance();
    }
    Properties props = new Properties();
    InputStream is = HibernateTestRunner.class.getResourceAsStream(mode);
    if (is == null) {
        throw new IllegalArgumentException("No configuration available at classpath:" + mode);
    }
    props.load(is);
    cfg.setProperties(props);
    sessionFactory = cfg.buildSessionFactory();
    session = sessionFactory.openSession();
    session.beginTransaction();
}

From source file:com.netspective.medigy.util.HibernateUtil.java

License:Open Source License

public static void setConfiguration(Configuration cfg) throws HibernateException {
    try {//from w ww  . j  av  a2s.  c  o m
        sessionFactory = cfg.buildSessionFactory();
        connectionProvider = ConnectionProviderFactory.newConnectionProvider(cfg.getProperties());
    } catch (MappingException e) {
        throw e;
    }
}

From source file:com.nominanuda.hibernate.HibernateConfiguration.java

License:Apache License

public SessionFactory getSessionFactory() {
    if (sessionFactory == null) {
        Configuration cfg = getConfiguration();
        sessionFactory = cfg.buildSessionFactory();//serviceRegistry
    }/*from  ww  w  .  j a v  a  2s  .  co m*/
    return sessionFactory;
}

From source file:com.oneandone.relesia.database.util.HibernateUtil.java

License:Apache License

private static SessionFactory buildSessionFactory() {
    try {//from  w ww  . ja va 2  s .co m
        if (sessionFactory == null) {
            Configuration configuration = new Configuration()
                    .configure(HibernateUtil.class.getResource("/db/hibernate.cfg.xml"));
            sessionFactory = configuration.buildSessionFactory();//serviceRegistry);
        }
        return sessionFactory;
    } catch (Throwable ex) {
        System.err.println("Initial SessionFactory creation failed." + ex);
        throw new ExceptionInInitializerError(ex);
    }
}

From source file:com.opengamma.util.test.HibernateTest.java

License:Open Source License

@BeforeMethod
public void setUp() throws Exception {
    super.setUp();

    Configuration configuration = getDbTool().getTestHibernateConfiguration();
    for (Class<?> clazz : getHibernateMappingClasses()) {
        configuration.addClass(clazz);/*  w  w w  .j  a v  a2s . co  m*/
    }

    SessionFactory sessionFactory = configuration.buildSessionFactory();
    setSessionFactory(sessionFactory);
}

From source file:com.openkm.dao.HibernateUtil.java

License:Open Source License

/**
 * Get instance/*from  w w  w .  j a  va 2s  .co  m*/
 */
public static SessionFactory getSessionFactory(String hbm2ddl) {
    if (sessionFactory == null) {
        try {
            // Configure Hibernate
            Configuration cfg = getConfiguration().configure();
            cfg.setProperty("hibernate.dialect", Config.HIBERNATE_DIALECT);
            cfg.setProperty("hibernate.connection.datasource", Config.HIBERNATE_DATASOURCE);
            cfg.setProperty("hibernate.hbm2ddl.auto", hbm2ddl);
            cfg.setProperty("hibernate.show_sql", Config.HIBERNATE_SHOW_SQL);
            cfg.setProperty("hibernate.generate_statistics", Config.HIBERNATE_STATISTICS);
            cfg.setProperty("hibernate.search.analyzer", Config.HIBERNATE_SEARCH_ANALYZER);
            cfg.setProperty("hibernate.search.default.directory_provider",
                    "org.hibernate.search.store.FSDirectoryProvider");
            cfg.setProperty("hibernate.search.default.indexBase", Config.HIBERNATE_SEARCH_INDEX_HOME);
            cfg.setProperty("hibernate.search.default.exclusive_index_use",
                    Config.HIBERNATE_SEARCH_INDEX_EXCLUSIVE);
            cfg.setProperty("hibernate.search.default.optimizer.operation_limit.max", "500");
            cfg.setProperty("hibernate.search.default.optimizer.transaction_limit.max", "75");
            cfg.setProperty("hibernate.worker.execution", "async");

            // http://relation.to/Bloggers/PostgreSQLAndBLOBs
            // cfg.setProperty("hibernate.jdbc.use_streams_for_binary", "false");

            // Show configuration
            log.info("Hibernate 'hibernate.dialect' = {}", cfg.getProperty("hibernate.dialect"));
            log.info("Hibernate 'hibernate.connection.datasource' = {}",
                    cfg.getProperty("hibernate.connection.datasource"));
            log.info("Hibernate 'hibernate.hbm2ddl.auto' = {}", cfg.getProperty("hibernate.hbm2ddl.auto"));
            log.info("Hibernate 'hibernate.show_sql' = {}", cfg.getProperty("hibernate.show_sql"));
            log.info("Hibernate 'hibernate.generate_statistics' = {}",
                    cfg.getProperty("hibernate.generate_statistics"));
            log.info("Hibernate 'hibernate.search.default.directory_provider' = {}",
                    cfg.getProperty("hibernate.search.default.directory_provider"));
            log.info("Hibernate 'hibernate.search.default.indexBase' = {}",
                    cfg.getProperty("hibernate.search.default.indexBase"));

            if (HBM2DDL_CREATE.equals(hbm2ddl)) {
                // In case of database schema creation, also clean filesystem data.
                // This means, conversion cache, file datastore and Lucene indexes.
                log.info("Cleaning filesystem data from: {}", Config.REPOSITORY_HOME);
                FileUtils.deleteQuietly(new File(Config.REPOSITORY_HOME));
            }

            // Create database schema, if needed
            sessionFactory = cfg.buildSessionFactory();

            if (HBM2DDL_CREATE.equals(hbm2ddl)) {
                log.info("Executing specific import for: {}", Config.HIBERNATE_DIALECT);
                InputStream is = ConfigUtils.getResourceAsStream("default.sql");
                String adapted = DatabaseDialectAdapter.dialectAdapter(is, Config.HIBERNATE_DIALECT);
                executeSentences(new StringReader(adapted));
                IOUtils.closeQuietly(is);
            }

            if (HBM2DDL_CREATE.equals(hbm2ddl) || HBM2DDL_UPDATE.equals(hbm2ddl)) {
                // Create or update translations
                for (String res : ConfigUtils.getResources("i18n")) {
                    String oldTrans = null;
                    String langId = null;

                    // Preserve translation changes
                    if (HBM2DDL_UPDATE.equals(hbm2ddl)) {
                        langId = FileUtils.getFileName(res);
                        log.info("Preserving translations for: {}", langId);
                        oldTrans = preserveTranslations(langId);
                    }

                    InputStream isLang = ConfigUtils.getResourceAsStream("i18n/" + res);
                    log.info("Importing translation: {}", res);
                    executeSentences(new InputStreamReader(isLang));
                    IOUtils.closeQuietly(isLang);

                    // Apply previous translation changes
                    if (HBM2DDL_UPDATE.equals(hbm2ddl)) {
                        if (oldTrans != null) {
                            log.info("Restoring translations for: {}", langId);
                            executeSentences(new StringReader(oldTrans));
                        }
                    }
                }

                // Replace "create" or "update" by "none" to prevent repository reset on restart
                if (Boolean.parseBoolean(Config.HIBERNATE_CREATE_AUTOFIX)) {
                    log.info("Executing Hibernate create autofix");
                    hibernateCreateAutofix(Config.HOME_DIR + "/" + Config.OPENKM_CONFIG);
                } else {
                    log.info("Hibernate create autofix not executed because of {}={}",
                            Config.PROPERTY_HIBERNATE_CREATE_AUTOFIX, Config.HIBERNATE_CREATE_AUTOFIX);
                }
            }
        } catch (HibernateException e) {
            log.error(e.getMessage(), e);
            throw new ExceptionInInitializerError(e);
        } catch (URISyntaxException e) {
            log.error(e.getMessage(), e);
            throw new ExceptionInInitializerError(e);
        } catch (IOException e) {
            log.error(e.getMessage(), e);
            throw new ExceptionInInitializerError(e);
        }
    }

    return sessionFactory;
}

From source file:com.openkm.hibernate.HibernateUtil.java

License:Open Source License

/**
 * Get instance/* ww w.  j  ava  2 s.  com*/
 */
public static SessionFactory getSessionFactory(Configuration cfg) {
    if (sessionFactory == null) {
        try {
            // Configuration
            cfg.setProperty("hibernate.dialect", "org.hibernate.dialect.HSQLDialect");
            cfg.setProperty("hibernate.connection.driver_class", "org.hsqldb.jdbcDriver");
            cfg.setProperty("hibernate.connection.url", "jdbc:hsqldb:mem:openkm");
            cfg.setProperty("hibernate.connection.username", "sa");
            cfg.setProperty("hibernate.connection.password", "");
            cfg.setProperty("hibernate.connection.pool_size", "1");
            cfg.setProperty("hibernate.connection.autocommit", "true");
            cfg.setProperty("hibernate.cache.provider_class", "org.hibernate.cache.HashtableCacheProvider");
            cfg.setProperty("hibernate.hbm2ddl.auto", "create");
            cfg.setProperty("hibernate.show_sql", "false");
            cfg.setProperty("hibernate.format_sql", "true");
            cfg.setProperty("hibernate.use_sql_comments", "true");

            // Hibernate Search
            cfg.setProperty("hibernate.search.default.directory_provider",
                    "org.hibernate.search.store.FSDirectoryProvider");
            cfg.setProperty("hibernate.search.default.indexBase", "indexes");

            sessionFactory = cfg.buildSessionFactory();
        } catch (HibernateException e) {
            log.error(e.getMessage(), e);
            throw new ExceptionInInitializerError(e);
        }
    }

    return sessionFactory;
}

From source file:com.oracle.coherence.hibernate.cachestore.HibernateCacheLoader.java

License:CDDL license

/**
 * Constructor which accepts an entityName. Configures Hibernate using
 * the default Hibernate configuration. The current implementation parses
 * this file once-per-instance (there is typically a single instance per).
 *
 * @param sEntityName    the Hibernate entity (i.e., the HQL table name)
 *//*from www. j  a v  a  2 s  . c  om*/
public HibernateCacheLoader(String sEntityName) {
    m_sEntityName = sEntityName;

    // Configure using the default Hibernate configuration.
    Configuration configuration = new Configuration();
    configuration.configure();

    m_sessionFactory = configuration.buildSessionFactory();
}