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.gemstone.gemfire.modules.HibernateJUnitTest.java

License:Apache License

public static SessionFactory getSessionFactory(Properties overrideProps) {
    System.setProperty(DistributionConfig.GEMFIRE_PREFIX + "home", "GEMFIREHOME");
    Configuration cfg = new 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:test");
    cfg.setProperty("hibernate.connection.url", jdbcURL);
    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.hbm2ddl.auto", "update");

    cfg.setProperty("hibernate.cache.region.factory_class",
            "com.gemstone.gemfire.modules.hibernate.GemFireRegionFactory");
    cfg.setProperty("hibernate.show_sql", "true");
    cfg.setProperty("hibernate.cache.use_query_cache", "true");
    //cfg.setProperty("gemfire.mcast-port", AvailablePort.getRandomAvailablePort(AvailablePort.JGROUPS)+"");
    cfg.setProperty(DistributionConfig.GEMFIRE_PREFIX + MCAST_PORT, "0");
    cfg.setProperty(DistributionConfig.GEMFIRE_PREFIX + STATISTIC_SAMPLING_ENABLED, "true");
    cfg.setProperty(DistributionConfig.GEMFIRE_PREFIX + LOG_FILE, gemfireLog);
    cfg.setProperty(DistributionConfig.GEMFIRE_PREFIX + "writable-working-dir", tmpDir.getPath());
    //cfg.setProperty("gemfire.statistic-archive-file", "plugin-stats-file.gfs");
    //cfg.setProperty("gemfire.default-client-region-attributes-id", "CACHING_PROXY");
    //cfg.setProperty("gemfire.cache-topology", "client-server");
    //cfg.setProperty("gemfire.locators", "localhost[5432]");
    //cfg.setProperty("gemfire.log-level", "fine");
    // cfg.setProperty("", "");
    cfg.addClass(Person.class);
    cfg.addClass(Event.class);
    if (overrideProps != null) {
        Iterator it = overrideProps.keySet().iterator();
        while (it.hasNext()) {
            String key = (String) it.next();
            cfg.setProperty(key, overrideProps.getProperty(key));
        }//from w  ww. ja v  a2  s.c  o m
    }
    return cfg.buildSessionFactory();
}

From source file:com.getReport.java

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    Configuration cfg = new Configuration();
    cfg.configure("hibernate.cfg.xml");//populates the data of the configuration file  
    SessionFactory factory = cfg.buildSessionFactory();
    int count = Integer.parseInt(request.getParameter("c"));
    city = request.getParameter("city");
    Session session1 = factory.openSession();
    // //from   ww  w. j  a v a 2  s.c  o  m

    try {
        if (count == 1) {

            Transaction t = session1.beginTransaction();
            List list = session1.createQuery(" from com.Donar").list();
            Iterator iterator = list.iterator();

            for (int i = 0; i < list.size(); i++) {
                Donar user = (Donar) iterator.next();

                if (user.getCity().equals(city)) {
                    d++;
                }

            }
            t.commit();

            Transaction t2 = session1.beginTransaction();
            List list2 = session1.createQuery(" from com.User").list();
            Iterator iterator2 = list2.iterator();

            for (int i = 0; i < list2.size(); i++) {
                User user = (User) iterator2.next();

                if (user.getCity().equals(city)) {
                    reg++;
                }

            }
            t2.commit();

            request.setAttribute("count", "2");
            request.setAttribute("reg", reg);
            request.setAttribute("donate", d);
            request.setAttribute("city", city);
            reg = 0;
            d = 0;
            city = "";

            //    RequestDispatcher rd = request.getRequestDispatcher("get.jsp");
            //    rd.forward(request, response);

        }

        else if (count == 2) {

            DateFormat formatter = new SimpleDateFormat("MM-DD-YYYY");

            String dat = request.getParameter("date");
            Date date = (Date) formatter.parse(dat);

            out.println(date);
            out.print("<br>");
            int day = date.getDay();
            int month = date.getMonth();
            out.print(day);
            out.print("<br>");
            out.print(month);

            Transaction t = session1.beginTransaction();
            List list = session1.createQuery(" from com.Donar").list();
            Iterator iterator = list.iterator();

            for (int i = 0; i < list.size(); i++) {
                Donar user = (Donar) iterator.next();

                if (user.getCity().equals(city)) {
                    d++;
                }

            }
            t.commit();

            Transaction t2 = session1.beginTransaction();
            List list2 = session1.createQuery(" from com.User").list();
            Iterator iterator2 = list2.iterator();

            for (int i = 0; i < list2.size(); i++) {
                User user = (User) iterator2.next();

                if (user.getCity().equals(city)) {
                    reg++;
                }

            }
            t2.commit();

            request.setAttribute("count", "1");
            request.setAttribute("reg", reg);
            request.setAttribute("donate", d);
            request.setAttribute("city", city);
            reg = 0;
            d = 0;
            city = "";

            //    RequestDispatcher rd = request.getRequestDispatcher("get.jsp");
            //    rd.forward(request, response);

        }

    } catch (Exception e) {
        out.print("eroor");
        e.printStackTrace();

    }

}

From source file:com.globalsight.ling.tm3.tools.TM3Command.java

License:Apache License

protected SessionFactory getSessionFactory(CommandLine command) {
    String username = null, password = null, connStr = null;
    // Order of operations:
    // - start with defaults
    // - load the file specified with -properties (if set), or the
    // default properties file.
    // - Look for command line options to override.
    if (command.hasOption(PROPERTIES)) {
        loadPropertiesFromFile(properties, command.getOptionValue(PROPERTIES), true);
    } else {/*from  w w w .j a v a  2  s.c  o m*/
        loadDefaultProperties(properties);
    }
    // Override any file properties with things passed on the command line
    Properties overrideProps = command.getOptionProperties(PROPERTY);
    for (Map.Entry<Object, Object> e : overrideProps.entrySet()) {
        properties.setProperty((String) e.getKey(), (String) e.getValue());
    }

    username = properties.getProperty(TM3_USER_PROPERTY);
    password = properties.getProperty(TM3_PASSWORD_PROPERTY);
    connStr = properties.getProperty(TM3_CONNECTION_PROPERTY);
    if (username == null || password == null || connStr == null) {
        usage("Must specify " + TM3_USER_PROPERTY + ", " + TM3_PASSWORD_PROPERTY + ", and "
                + TM3_CONNECTION_PROPERTY + " with -Dprop=val or via properties file");
    }

    Properties hibernateProps = new Properties(properties);
    hibernateProps.put("hibernate.dialect", "org.hibernate.dialect.MySQLInnoDBDialect");
    hibernateProps.put("hibernate.connection.driver_class", "com.mysql.jdbc.Driver");
    hibernateProps.put("hibernate.connection.url", connStr);
    hibernateProps.put("hibernate.connection.username", username);
    hibernateProps.put("hibernate.connection.password", password);
    hibernateProps.put("hibernate.cglib.use_reflection_optimizer", "false"); // this
                                                                             // is
                                                                             // default
                                                                             // in
                                                                             // hibernate
                                                                             // 3.2
    hibernateProps.put("hibernate.show_sql", "false");
    hibernateProps.put("hibernate.format_sql", "false");
    hibernateProps.put("hibernate.connection.pool_size", "1");
    hibernateProps.put("hibernate.cache.provider_class", "org.hibernate.cache.HashtableCacheProvider");
    // A little sketchy. Due to some undocumented (?) Hibernate
    // behavior, it will pick up hibernate cfg properties from elsewhere
    // in the classpath, even though we've specified them by hand.
    // As a result, this may end up unintentionally running c3p0
    // connection pooling, which will release connections on commit.
    // This causes problems for multi-transaction commands (like
    // GlobalSight's migrate-tm), because it will kill the connection
    // in mid-operation. As a result, we force the release mode to
    // keep the connection open until we're done.
    hibernateProps.put("hibernate.connection.release_mode", "on_close");
    Configuration cfg = new Configuration().addProperties(hibernateProps);
    cfg = HibernateConfig.extendConfiguration(cfg);
    if (requiresDataFactory()) {
        cfg = getDataFactory().extendConfiguration(cfg);
    }

    return cfg.buildSessionFactory();
}

From source file:com.googlecode.osde.internal.Activator.java

License:Apache License

public void connect(final IWorkbenchWindow window) {
    logger.info("Connecting to Shindig database");
    Job job = new Job("Connecting to Shindig database.") {
        @Override//from w  ww. j a v  a 2s .  c om
        protected IStatus run(IProgressMonitor monitor) {
            monitor.beginTask("Connecting to Shindig database.", 4);
            monitor.subTask("Building Hibernate SessionFactory.");
            File configFile = new File(HibernateUtils.configFileDir, HibernateUtils.configFileName);
            Configuration configure = new AnnotationConfiguration().configure(configFile);
            sessionFactory = configure.buildSessionFactory();
            monitor.worked(1);
            monitor.subTask("Opening Hibernate session.");
            session = sessionFactory.openSession();
            monitor.worked(1);
            monitor.subTask("Creating services.");
            personService = new PersonService(session);
            applicationService = new ApplicationService(session);
            appDataService = new AppDataService(session);
            activityService = new ActivityService(session);
            monitor.worked(1);
            monitor.subTask("Notify each view about connecting with database.");
            window.getShell().getDisplay().syncExec(new Runnable() {
                public void run() {
                    try {
                        PersonView personView = (PersonView) window.getActivePage().showView(PersonView.ID,
                                null, IWorkbenchPage.VIEW_CREATE);
                        personView.connectedDatabase();
                        AppDataView appDataView = (AppDataView) window.getActivePage().showView(AppDataView.ID,
                                null, IWorkbenchPage.VIEW_CREATE);
                        appDataView.connectedDatabase();
                        ActivitiesView activitiesView = (ActivitiesView) window.getActivePage()
                                .showView(ActivitiesView.ID, null, IWorkbenchPage.VIEW_CREATE);
                        activitiesView.connectedDatabase();
                        UserPrefsView userPrefsView = (UserPrefsView) window.getActivePage()
                                .showView(UserPrefsView.ID, null, IWorkbenchPage.VIEW_CREATE);
                        userPrefsView.connectedDatabase();
                        ApplicationView applicationView = (ApplicationView) window.getActivePage()
                                .showView(ApplicationView.ID, null, IWorkbenchPage.VIEW_CREATE);
                        applicationView.connectedDatabase();
                    } catch (PartInitException e) {
                        logger.error("Connecting to Shindig Database failed.", e);
                    } catch (JDBCException e) {
                        MessageDialog.openError(window.getShell(), "Error",
                                "Database connection failed.\n  Cause: " + e.getErrorCode() + ": "
                                        + e.getSQLException().getMessage());
                    } catch (HibernateException e) {
                        MessageDialog.openError(window.getShell(), "Error",
                                "Database connection failed.\n  Cause: " + e.getMessage());
                    }
                }
            });
            monitor.worked(1);
            monitor.done();
            return Status.OK_STATUS;
        }
    };
    job.schedule();
}

From source file:com.googlecode.sarasvati.example.hib.HibTestSetup.java

License:Open Source License

public static void init(final boolean createSchema) throws Exception {
    final Configuration config = new Configuration();

    if (createSchema) {
        config.setProperty(Environment.HBM2DDL_AUTO, "create-drop");
    }/*from w w  w  .  j  av  a2  s.c o m*/

    HibEngine.addToConfiguration(config, false);

    config.addAnnotatedClass(HibExampleTaskNode.class);
    config.addAnnotatedClass(Task.class);
    config.addAnnotatedClass(InitNode.class);
    config.addAnnotatedClass(DumpNode.class);
    config.addAnnotatedClass(AsyncNode.class);

    URL url = HibTestSetup.class.getClassLoader().getResource("hibernate.cfg.xml");

    if (url == null) {
        System.out.println("ERROR: No hibernate.cfg.xml found in classpath!\n"
                + "\tIn order to run the examples, you must create hibernate.cfg.xml in the examples/ directory.\n"
                + "\tYou can use the entries in conf/ as a starting point.");
        System.exit(-1);
    }

    config.configure(url);
    sessionFactory = config.buildSessionFactory();
}

From source file:com.hazelcast.hibernate.HibernateTestSupport.java

License:Open Source License

protected SessionFactory createSessionFactory(Properties props, IHazelcastInstanceLoader customInstanceLoader) {
    Configuration conf = new Configuration();
    URL xml = HibernateTestSupport.class.getClassLoader().getResource("test-hibernate.cfg.xml");
    props.put(CacheEnvironment.EXPLICIT_VERSION_CHECK, "true");
    if (customInstanceLoader != null) {
        props.put("com.hazelcast.hibernate.instance.loader", customInstanceLoader);
        customInstanceLoader.configure(props);
    } else {// ww  w  . jav a  2  s. c  o m
        props.remove("com.hazelcast.hibernate.instance.loader");
    }
    conf.configure(xml);
    conf.setCacheConcurrencyStrategy(DummyEntity.class.getName(), getCacheStrategy());
    conf.setCacheConcurrencyStrategy(DummyProperty.class.getName(), getCacheStrategy());
    conf.setCollectionCacheConcurrencyStrategy(DummyEntity.class.getName() + ".properties", getCacheStrategy());
    conf.addProperties(props);
    final SessionFactory sf = conf.buildSessionFactory();
    sf.getStatistics().setStatisticsEnabled(true);
    return sf;
}

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

License:Open Source License

public static SessionFactory configure() {
    try {//from www. j  a  v a 2  s . c  o m
        Logger loggerRoot = Logger.getLogger(HibernateUtil.class.getName());
        Logger loggerConnect = Logger.getLogger("Connect");

        loggerRoot.fine("In HibernateUtil try-clause");
        loggerRoot.warning("In HibernateUtil try-clause");
        loggerConnect.fine("In HibernateUtil try-clause via loggerConnect DEBUG*****");

        // Create the SessionFactory from hibernate.cfg.xml
        Properties properties = getProperties();

        Configuration configuration = new Configuration();
        configuration.setProperties(properties);
        return configuration.buildSessionFactory();
    } 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);
    }
}

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

License:Open Source License

private static SessionFactory configure(String cfgPath) {
    try {/*  ww w  . j  av  a  2  s .co m*/

        Configuration configuration = new AnnotationConfiguration();

        if (cfgPath == null)
            configuration.configure();
        else
            configuration.configure(cfgPath);

        return configuration.buildSessionFactory();

    } catch (Throwable ex) {

        Logger.getLogger(HibernateUtil.class.getName()).log(Level.SEVERE,
                "Initial SessionFactory creation failed for cfg path: " + cfgPath, ex);
        throw new ExceptionInInitializerError(ex);
    }
}

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

License:Open Source License

/**
 * Get instance/*from   w  w  w.j  av  a 2 s  .c om*/
 */
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.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);
                executeImport(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);
                    executeImport(new InputStreamReader(isLang));
                    IOUtils.closeQuietly(isLang);

                    // Apply previous translation changes
                    if (HBM2DDL_UPDATE.equals(hbm2ddl)) {
                        if (oldTrans != null) {
                            log.info("Restoring translations for: {}", langId);
                            executeImport(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.ikon_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.ikon.dao.HibernateUtil.java

License:Open Source License

/**
 * Get instance// ww w  .  j  a va2 s  .  c om
 */
public static SessionFactory getSessionFactory(Configuration cfg) {
    if (sessionFactory == null) {
        sessionFactory = cfg.buildSessionFactory();
    }

    return sessionFactory;
}