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:edu.pitt.dbmi.facebase.hd.MySQLHibernateConfigurationHd.java

License:Open Source License

private SessionFactory getSessionFactory() {
    log.debug("MySQLHibernateConfigurationHd.getSessionFactory() called.");
    if (lclSessionFactoryHd != null)
        return (lclSessionFactoryHd);

    try {/*from   w w  w.  ja  v a 2 s . com*/
        boolean validConnection = false;
        try {
            DriverManager.registerDriver(new com.mysql.jdbc.Driver());
            Connection conn = DriverManager.getConnection(connectionURL, username, password);
            conn.close();
            validConnection = true;
        } catch (Exception e) {
            String errorString = "Cannot connect to database at " + connectionURL + " with username "
                    + username;
            String logString = e.getMessage();
            edu.pitt.dbmi.facebase.hd.HumanDataController.addError(errorString, logString);
            log.error(errorString, e);
            return (null);
        }

        if (validConnection) {
            Configuration hibernateConfHd = null;
            hibernateConfHd = new Configuration();
            String className = null;
            try {
                hibernateConfHd.addAnnotatedClass(FbKey.class);
            } catch (Exception ex) {
                String errorString = "Unable to load annotated class for hibernate: " + className;
                String logString = ex.getMessage();
                edu.pitt.dbmi.facebase.hd.HumanDataController.addError(errorString, logString);
                log.error(errorString, ex);
            }

            hibernateConfHd.setProperty("hibernate.connection.driver_class", "com.mysql.jdbc.Driver")
                    .setProperty("hibernate.connection.url", connectionURL)
                    .setProperty("hibernate.dialect", "org.hibernate.dialect.MySQLDialect")
                    .setProperty("hibernate.connection.username", username)
                    .setProperty("hibernate.connection.password", password)
                    .setProperty("hibernate.show_sql", "false")
                    .setProperty("hibernate.current_session_context_class", "thread")
                    .setProperty("hibernate.connection.provider_class",
                            "org.hibernate.connection.C3P0ConnectionProvider")
                    .setProperty("hibernate.c3p0.acquire_increment", "1")
                    .setProperty("hibernate.c3p0.idle_test_period", "240")
                    .setProperty("hibernate.c3p0.timeout", "600").setProperty("hibernate.c3p0.max_size", "100")
                    .setProperty("hibernate.c3p0.min_size", "3")
                    .setProperty("hibernate.c3p0.validate",
                            "false") /*this is an expensive property to turn on...*/
                    .setProperty("hibernate.c3p0.max_statements", "500")
                    .setProperty("hibernate.cache.use_second_level_cache", "false")
                    .setProperty("hibernate.jdbc.batch.size", "20");

            lclSessionFactoryHd = hibernateConfHd.buildSessionFactory();

        }

    } catch (Throwable ex) {
        String errorString = "Initial SessionFactory creation failed.";
        String logString = ex.getMessage();
        edu.pitt.dbmi.facebase.hd.HumanDataController.addError(errorString, logString);
        log.error(errorString, ex);
        throw new ExceptionInInitializerError(ex);
    }

    return (lclSessionFactoryHd);
}

From source file:edu.sjsu.cmpe275.lab2.model.HibernateUtil.java

License:Open Source License

@Bean
public static SessionFactory getSessionFactory() {
    if (sessionFactory == null) {
        //initialize one factory
        try {/*  w  w w .  jav a2 s  .  com*/
            Configuration configuration = new Configuration().configure();
            // StandardServiceRegistryBuilder builder= new StandardServiceRegistryBuilder().applySettings(configuration.getProperties());
            // ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();
            //sessionFactory = configuration.buildSessionFactory( builder.build());
            sessionFactory = configuration.buildSessionFactory();
        } catch (Throwable e) {
            throw new ExceptionInInitializerError(e);
        }
    }
    return sessionFactory;

}

From source file:edu.upenn.cis.ppod.persistence.SessionFactoryProvider.java

License:Apache License

public SessionFactory get() {
    logger.debug("building session factory...");
    final Configuration cfg = new Configuration();
    cfg.setNamingStrategy(new ImprovedNamingStrategy());

    // Read hibernate.cfg.xml (has to be present)
    cfg.configure();// www  .  j a  v a 2 s .c o m
    final SessionFactory sf = cfg.buildSessionFactory();
    logger.debug("...done");
    return sf;
}

From source file:edu.usf.cutr.gtfsrtvalidator.db.GTFSHibernate.java

License:Open Source License

private static HibernateGtfsFactory createHibernateGtfsFactory(String resource) {
    Configuration config = new Configuration();

    if (resource.startsWith(KEY_CLASSPATH)) {
        resource = resource.substring(KEY_CLASSPATH.length());
        config = config.configure(resource);
    } else if (resource.startsWith(KEY_FILE)) {
        resource = resource.substring(KEY_FILE.length());
        config = config.configure(new File(resource));
    } else {/*  w  w w  .  j  a  v  a  2s .c  o  m*/
        config = config.configure(new File(resource));
    }

    SessionFactory sessionFactory = config.buildSessionFactory();
    return new HibernateGtfsFactory(sessionFactory);
}

From source file:edu.wustl.dao.daofactory.DAOFactory.java

License:BSD License

/**
 *This method will be called to build the session factory.
 *It reads the configuration file ,build the sessionFactory and configuration object
 *and set the connection manager.//from  w ww.j a v a  2  s .  c om
 *@throws DAOException :Generic DAOException.
 */
public void buildSessionFactory() throws DAOException {
    try {
        Configuration configuration = setConfiguration(configurationFile);
        SessionFactory sessionFactory = configuration.buildSessionFactory();
        setConnectionManager(sessionFactory, configuration);
    } catch (Exception exp) {
        logger.fatal(exp.getMessage());
        logger.error(exp.getMessage(), exp);
        ErrorKey errorKey = ErrorKey.getErrorKey("db.operation.error");
        throw new DAOException(errorKey, exp, "DAOFactory.java :" + DAOConstants.BUILD_SESS_FACTORY_ERR);

    }
}

From source file:entidades.util.HibernateUtil.java

private static SessionFactory buildSessionFactory() {
    try {//from w  ww  .  j  av  a2 s  .  co  m
        Configuration cfg = new Configuration();
        cfg.configure("hibernate.cfg.xml");
        return cfg.buildSessionFactory();
    } catch (Throwable e) {
        System.out.println("Error: " + e);
        throw new ExceptionInInitializerError(e);
    }
}

From source file:es.jpons.persistence.util.TemporalHibernateUtil.java

License:Open Source License

public static synchronized Session getSession(Properties configuration, List<Class> annotatedClasses) {

    //        if(instance==null){
    //            log.trace("Creating instance from properties");
    ////          setProperties(configuration);
    //          instance =  new TemporalHibernateUtil();
    //        }/*from   w w w  .  j  av  a 2s. c  o  m*/

    Configuration cfg = new AnnotationConfiguration();//.setProperties(configuration);//Configuration();
    cfg.setProperties(configuration);
    cfg.addPackage(configuration.getProperty("package.persistence"));
    // esta funcion parece interesante
    //cfg.addSqlFunction(rn, null);
    log.trace("Registering temporal interceptor");
    cfg.setInterceptor(new TemporalInterceptor());

    for (Class c : annotatedClasses) {
        cfg.addAnnotatedClass(c);
    }

    log.trace("Configuration from properties file");

    if (factory == null) {
        factory = cfg.buildSessionFactory();
    }

    log.trace("Session factory created");
    return factory.openSession();
}

From source file:eu.scape_project.tb.hibernate.HibernateSessionRequestFilter.java

License:Apache License

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {

    try {//from w ww  .  j a  v a 2s .  c  o m
        if (sf == null || sf.isClosed()) {
            if (sf != null) {
                sf.openSession();
            } else {
                Configuration configuration = new Configuration();
                sf = configuration.buildSessionFactory();
            }
        }
        logger.debug("Starting a database transaction");
        sf.getCurrentSession().beginTransaction();

        // Call the next filter (continue request processing)
        chain.doFilter(request, response);

        // Commit and cleanup
        logger.debug("Committing the database transaction");
        sf.getCurrentSession().getTransaction().commit();

    } catch (StaleObjectStateException staleEx) {
        logger.error("This interceptor does not implement optimistic concurrency control!");
        logger.error("Your application will not work until you add compensation actions!");
        // Rollback, close everything, possibly compensate for any permanent changes
        // during the conversation, and finally restart business conversation. Maybe
        // give the user of the application a chance to merge some of his work with
        // fresh data... what you do here depends on your applications design.
        throw staleEx;
    } catch (Throwable ex) {
        // Rollback only
        logger.error("Hibernate error", ex);
        try {
            if (sf.getCurrentSession().getTransaction().isActive()) {
                logger.debug("Trying to rollback database transaction after exception");
                sf.getCurrentSession().getTransaction().rollback();
            }
        } catch (Throwable rbEx) {
            logger.error("Could not rollback transaction after exception!", rbEx);
        }

        // Let others handle it... maybe another interceptor for exceptions?
        throw new ServletException(ex);
    }
}

From source file:fi.uta.infim.usaproxylogdb.Main.java

License:Open Source License

/**
 * @param args//from   www.  ja  va2 s. c om
 * @throws Throwable 
 */
@SuppressWarnings({ "deprecation" })
public static void main(String[] args) {

    printLicense();

    UsaProxyLog loki;

    try {
        System.out.print("Parsing log file... ");
        loki = new UsaProxyLogParser().parseLog(args[0]);
        System.out.println("done.");
    } catch (ArrayIndexOutOfBoundsException ae) {
        printError(ae, "Please provide a file name.", true, true);
        return;
    } catch (Exception e) {
        printError(e, "Unable to parse log file.", true, true);
        return;
    }

    SessionFactory sf;

    try {
        System.out.print("Establishing database connection... ");
        Configuration cfg = new Configuration().configure(new File("hibernate.cfg.xml"))
                .addURL(UsaProxyLog.class.getResource("/META-INF/orm.xml"));
        sf = cfg.buildSessionFactory();
        System.out.println("done.");
    } catch (Exception e) {
        printError(e, "Unable to configure database connectivity. Check your configuration.", true, true);
        return;
    }

    try {
        System.out.print("Persisting log contents... ");
        Session s = sf.openSession();
        Transaction tx = s.beginTransaction();
        s.persist(loki);
        tx.commit();
        s.close();
        sf.close();
        System.out.println("done.");
    } catch (Exception e) {
        printError(e, "Unable to persist data.", true, true);
        return;
    }
}

From source file:fr.lemet.gtfs.GtfsBase.java

License:Apache License

public static HibernateGtfsFactory createHibernateGtfsFactory(String resource) {

    Configuration config = new Configuration();

    if (resource.startsWith(KEY_CLASSPATH)) {
        resource = resource.substring(KEY_CLASSPATH.length());
        config = config.configure(resource);
    } else if (resource.startsWith(KEY_FILE)) {
        resource = resource.substring(KEY_FILE.length());
        config = config.configure(new File(resource));
    } else {/*w  ww.jav  a 2  s.c o m*/
        config = config.configure(new File(resource));
    }

    SessionFactory sessionFactory = config.buildSessionFactory();
    return new HibernateGtfsFactory(sessionFactory);
}