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.redhat.rhn.common.hibernate.ConnectionManager.java

License:Open Source License

/**
 * Create a SessionFactory, loading the hbm.xml files from the specified
 * location.//from  w ww  .jav a  2s . c  o m
 * @param packageNames Package name to be searched.
 */
private void createSessionFactory() {
    if (sessionFactory != null && !sessionFactory.isClosed()) {
        return;
    }

    List<String> hbms = new LinkedList<String>();

    for (Iterator<String> iter = packageNames.iterator(); iter.hasNext();) {
        String pn = iter.next();
        hbms.addAll(FinderFactory.getFinder(pn).find("hbm.xml"));
        if (LOG.isDebugEnabled()) {
            LOG.debug("Found: " + hbms);
        }
    }

    try {
        Configuration config = new Configuration();
        /*
         * Let's ask the RHN Config for all properties that begin with
         * hibernate.*
         */
        LOG.info("Adding hibernate properties to hibernate Configuration");
        Properties hibProperties = Config.get().getNamespaceProperties("hibernate");
        hibProperties.put("hibernate.connection.username", Config.get().getString(ConfigDefaults.DB_USER));
        hibProperties.put("hibernate.connection.password", Config.get().getString(ConfigDefaults.DB_PASSWORD));

        hibProperties.put("hibernate.connection.url", ConfigDefaults.get().getJdbcConnectionString());

        config.addProperties(hibProperties);
        // Force the use of our txn factory
        if (config.getProperty(Environment.TRANSACTION_STRATEGY) != null) {
            throw new IllegalArgumentException("The property " + Environment.TRANSACTION_STRATEGY
                    + " can not be set in a configuration file;" + " it is set to a fixed value by the code");
        }

        for (Iterator<String> i = hbms.iterator(); i.hasNext();) {
            String hbmFile = i.next();
            if (LOG.isDebugEnabled()) {
                LOG.debug("Adding resource " + hbmFile);
            }
            config.addResource(hbmFile);
        }
        if (configurators != null) {
            for (Iterator<Configurator> i = configurators.iterator(); i.hasNext();) {
                Configurator c = i.next();
                c.addConfig(config);
            }
        }

        // add empty varchar warning interceptor
        EmptyVarcharInterceptor interceptor = new EmptyVarcharInterceptor();
        interceptor.setAutoConvert(true);
        config.setInterceptor(interceptor);

        sessionFactory = config.buildSessionFactory();
    } catch (HibernateException e) {
        LOG.error("FATAL ERROR creating HibernateFactory", e);
    }
}

From source file:com.reg.java

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");

    String city = request.getParameter("city");
    String state = request.getParameter("state");
    String zip = request.getParameter("zip");
    String country = request.getParameter("country");
    String mob = request.getParameter("mob");
    String org = request.getParameter("mem");
    String total_pr = request.getParameter("total");
    int personCount = Integer.parseInt(total_pr);
    Date date = new Date();
    User u = new User();
    u.setCity(city);/*from  w w  w  .j  a  v  a2  s.com*/
    u.setCountry(country);
    u.setD(date);
    u.setMobile(mob);
    u.setOrganization(org);
    u.setState(state);
    u.setZipcode(zip);
    u.setPersonCount(personCount);

    try {
        Configuration cfg = new Configuration();
        cfg.configure("hibernate.cfg.xml");//populates the data of the configuration file  
        SessionFactory factory = cfg.buildSessionFactory();
        Session session = factory.openSession();
        Transaction t = session.beginTransaction();

        session.persist(u);
        t.commit();
        session.close();

        request.setAttribute("sendSuccess", "block");
        RequestDispatcher rd = request.getRequestDispatcher("Main.jsp");
        rd.forward(request, response);
    }

    catch (Exception e) {

        request.setAttribute("dbError", "block");
        RequestDispatcher rd = request.getRequestDispatcher("Main.jsp");
        rd.forward(request, response);

    }

}

From source file:com.sam.moca.db.hibernate.HibernateTools.java

License:Open Source License

synchronized public static SessionFactory getSessionFactory(final MocaContext ctx) {
    if (_factory == null) {
        Configuration cfg = new Configuration();

        // First, load up default properties stored in MOCA 
        Properties props = new Properties();
        try {//from   www.ja v  a2  s .co m
            _loadProperties(props, HibernateTools.class.getResourceAsStream("resources/hibernate.properties"));
        } catch (IOException e) {
            ctx.logWarning("Unable to load hibernate properties: " + e);
            _sqlLogger.debug("Unable to load hibernate properties", e);
        }

        // Next, default the database dialect, based on MOCA's idea
        // of the database type.
        String dbType = ctx.getDb().getDbType();

        if (dbType.equals("ORACLE")) {
            props.setProperty("hibernate.dialect", "org.hibernate.dialect.Oracle10gDialect");
        } else if (dbType.equals("MSSQL")) {
            props.setProperty("hibernate.dialect", "com.sam.moca.db.hibernate.UnicodeSQLServerDialect");
        } else if (dbType.equals("H2")) {
            props.setProperty("hibernate.dialect", "org.hibernate.dialect.H2Dialect");
        }

        SystemContext systemContext = ServerUtils.globalContext();

        // We get the data files in reverse.
        File[] files = systemContext.getDataFiles(new FilenameFilter() {

            @Override
            public boolean accept(File dir, String name) {
                if (name.equals("hibernate.properties")) {
                    return true;
                }
                return false;
            }

        }, true);

        // For each directory in the list, look for a
        // hibernate.properties file.
        for (File propFile : files) {
            if (propFile.canRead()) {
                try {
                    ctx.trace(MocaTrace.SQL, "Loading Properties file: " + propFile);
                    _loadProperties(props, new FileInputStream(propFile));
                } catch (IOException e) {
                    ctx.logWarning("Unable to load properties " + propFile + ": " + e);
                    _sqlLogger.debug("Unable to load hibernate properties", e);
                } catch (HibernateException e) {
                    ctx.logWarning("Unable to load properties " + propFile + ": " + e);
                    _sqlLogger.debug("Unable to load hibernate properties", e);
                }
            }
        }

        cfg.setProperties(props);

        // We get the data files in reverse.
        files = systemContext.getDataFiles(new FilenameFilter() {

            @Override
            public boolean accept(File dir, String name) {
                if (name.equals("hibernate.cfg.xml")) {
                    return true;
                }
                return false;
            }

        }, true);

        // Now look for hibernate config files in each mappings directory.
        for (File xmlFile : files) {
            if (xmlFile.canRead()) {
                try {
                    ctx.trace(MocaTrace.SQL, "Loading config file: " + xmlFile);
                    cfg.configure(xmlFile);
                } catch (HibernateException e) {
                    ctx.logWarning("Unable to load config file " + xmlFile + ": " + e);
                    _sqlLogger.debug("Unable to load hibernate config", e);
                }
            }
        }

        _factory = cfg.buildSessionFactory();

        StatisticsService statsMBean = new StatisticsService();
        statsMBean.setSessionFactory(_factory);

        Exception excp = null;
        MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
        try {
            mBeanServer.registerMBean(statsMBean, new ObjectName("Hibernate:application=Statistics"));
        } catch (InstanceAlreadyExistsException e) {
            excp = e;
        } catch (MBeanRegistrationException e) {
            excp = e;
        } catch (NotCompliantMBeanException e) {
            excp = e;
        } catch (MalformedObjectNameException e) {
            excp = e;
        }

        if (excp != null) {
            _sqlLogger.warn("Failed to export Hibernate Statistics "
                    + "Service.  Runtime statistics will not be viewable " + "from MBeans!", excp);
        }
    }

    return _factory;

}

From source file:com.sell.java

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");

    int moneyStock = 0;
    int money = 0;
    try {//w  ww.  ja  v a2  s. c  om
        HttpSession session = request.getSession(true);
        Configuration cfg = new Configuration();
        cfg.configure("hibernate.cfg.xml");//populates the data of the configuration file  
        SessionFactory factory = cfg.buildSessionFactory();
        Session session1 = factory.openSession();

        int p = (Integer) session.getAttribute("price");
        String UEmail = (String) session.getAttribute("email");

        Date d = new Date();

        int idx = Integer.parseInt(request.getParameter("i"));
        String comp = request.getParameter("comp");
        String Owner_email = request.getParameter("email");

        System.out.println("id" + idx);
        System.out.println("c" + comp);
        System.out.println("email" + Owner_email);

        Transaction t3 = session1.beginTransaction();
        List list = session1.createQuery("from com.ShareCom Where COMP ='" + comp + "'").list();
        Iterator iterator = list.iterator();

        for (int j = 0; j < list.size(); j++) {
            ShareCom user = (ShareCom) iterator.next();
            moneyStock = user.getShare_rate();

        }
        PrintWriter out = response.getWriter();

        t3.commit();

        Transaction t4 = session1.beginTransaction();
        List list1 = session1.createQuery("from com.StockUser Where EMAIL='" + Owner_email + "'").list();
        Iterator iterator1 = list1.iterator();

        for (int j = 0; j < list.size(); j++) {
            StockUser user = (StockUser) iterator1.next();
            money = user.getMoney();

        }
        t4.commit();
        ;

        money = money - moneyStock;
        Transaction t2 = session1.beginTransaction();
        session1.createSQLQuery(
                "UPDATE STOCK.STOCKUSER set MONEY=" + money + "   WHERE EMAIL='" + Owner_email + "' ")
                .executeUpdate();
        t2.commit();

        p = p + moneyStock;
        session.removeAttribute("price");
        session.setAttribute("price", p);
        Transaction t5 = session1.beginTransaction();
        session1.createSQLQuery("UPDATE STOCK.STOCKUSER set MONEY=" + p + "   WHERE EMAIL='" + UEmail + "' ")
                .executeUpdate();
        t5.commit();

        Transaction t1 = session1.beginTransaction();
        session1.createSQLQuery("UPDATE STOCK.ShareBuy set END_RATE=" + moneyStock + "   WHERE USEREMAIL='"
                + UEmail + "' AND ID=" + idx + " ").executeUpdate();
        t1.commit();

        Transaction t6 = session1.beginTransaction();
        session1.createSQLQuery("UPDATE STOCK.ShareBuy set STATUS='SOLD'   WHERE USEREMAIL='" + UEmail
                + "' AND ID=" + idx + " ").executeUpdate();
        t6.commit();

        Transaction to = session1.beginTransaction();
        TransactionT tra = new TransactionT();
        tra.setAmount(moneyStock);
        tra.setSellermail(UEmail);
        tra.setStatus("S-U");
        tra.setD(d);
        tra.setUsermail(Owner_email);
        session1.persist(tra);

        to.commit();

        System.out.println(idx);

        out.print("Success");

    } catch (Exception ee) {
        ee.printStackTrace();
    }

}

From source file:com.sos.hibernate.classes.SosHibernateSession.java

License:Apache License

public static Session getInstance(final File configurationFile) {
    if (session == null) {
        ClassLoader classLoader = ClassLoader.getSystemClassLoader();
        try {//from  www  . j  a v  a  2  s  . com
            Configuration configuration = new Configuration();
            try {
                Class dailyScheduleDBItem = classLoader
                        .loadClass("com.sos.dailyschedule.db.DailyScheduleDBItem");
                configuration.addAnnotatedClass(dailyScheduleDBItem);
            } catch (ClassNotFoundException e) {
            }
            try {
                Class schedulerTaskHistoryDBItem = classLoader
                        .loadClass("com.sos.scheduler.history.db.SchedulerTaskHistoryDBItem");
                configuration.addAnnotatedClass(schedulerTaskHistoryDBItem);
            } catch (ClassNotFoundException e) {
            }
            try {
                Class schedulerOrderStepHistoryDBItem = classLoader
                        .loadClass("com.sos.scheduler.history.db.SchedulerOrderStepHistoryDBItem");
                configuration.addAnnotatedClass(schedulerOrderStepHistoryDBItem);
            } catch (ClassNotFoundException e) {
            }
            try {
                Class schedulerOrderHistoryDBItem = classLoader
                        .loadClass("com.sos.scheduler.history.db.SchedulerOrderHistoryDBItem");
                configuration.addAnnotatedClass(schedulerOrderHistoryDBItem);
            } catch (ClassNotFoundException e) {
            }
            try {
                Class schedulerInstancesDBItem = classLoader
                        .loadClass("com.sos.scheduler.db.SchedulerInstancesDBItem");
                configuration.addAnnotatedClass(schedulerInstancesDBItem);
            } catch (ClassNotFoundException e) {
            }

            try {
                Class jadeFilesDBItem = classLoader.loadClass("sos.ftphistory.db.JadeFilesDBItem");
                configuration.addAnnotatedClass(jadeFilesDBItem);
            } catch (ClassNotFoundException e) {
            }

            try {
                Class JadeFilesHistoryDBItem = classLoader
                        .loadClass("sos.ftphistory.db.JadeFilesHistoryDBItem");
                configuration.addAnnotatedClass(JadeFilesHistoryDBItem);
            } catch (ClassNotFoundException e) {
            }

            try {
                Class SchedulerEventDBItem = classLoader.loadClass("com.sos.eventing.db.SchedulerEventDBItem");
                configuration.addAnnotatedClass(SchedulerEventDBItem);
            } catch (ClassNotFoundException e) {
            }

            try {
                Class jobNetPlanDBItem = classLoader.loadClass("com.sos.jobnet.db.JobNetPlanDBItem");
                configuration.addAnnotatedClass(jobNetPlanDBItem);
            } catch (ClassNotFoundException e) {
            }
            try {
                Class jobNetNodeDBItem = classLoader.loadClass("com.sos.jobnet.db.JobNetNodeDBItem");
                configuration.addAnnotatedClass(jobNetNodeDBItem);
            } catch (ClassNotFoundException e) {
            }
            try {
                Class jobNetEdgesDBItem = classLoader.loadClass("com.sos.jobnet.db.JobNetEdgesDBItem");
                configuration.addAnnotatedClass(jobNetEdgesDBItem);
            } catch (ClassNotFoundException e) {
            }

            try {
                Class eventsDBItem = classLoader.loadClass("com.sos.jobnet.db.EventsDBItem");
                configuration.addAnnotatedClass(eventsDBItem);
            } catch (ClassNotFoundException e) {
            }
            try {
                Class jobNetHistoryDBItem = classLoader.loadClass("com.sos.jobnet.db.JobNetHistoryDBItem");
                configuration.addAnnotatedClass(jobNetHistoryDBItem);
            } catch (ClassNotFoundException e) {
            }

            try {
                Class jobNetCmdHistoryDBItem = classLoader
                        .loadClass("com.sos.jobnet.db.JobNetCmdHistoryDBItem");
                configuration.addAnnotatedClass(jobNetCmdHistoryDBItem);
            } catch (ClassNotFoundException e) {
            }

            try {
                Class jobNetDBItem = classLoader.loadClass("com.sos.jobnet.db.JobNetDBItem");
                configuration.addAnnotatedClass(jobNetDBItem);
            } catch (ClassNotFoundException e) {
            }

            // Configuration configuration = new Configuration();
            // Configuration configuration = new
            // Configuration().addAnnotatedClass(dailyScheduleDBItem).addAnnotatedClass(schedulerTaskHistoryDBItem).addAnnotatedClass(schedulerOrderStepHistoryDBItem)
            // .addAnnotatedClass(schedulerOrderHistoryDBItem).addAnnotatedClass(schedulerInstancesDBItem).addAnnotatedClass(jobNetPlanDBItem).addAnnotatedClass(jobNetNodeDBItem).addAnnotatedClass(jobNetEdgesDBItem);
            configuration.configure(configurationFile);
            /*
             * serviceRegistry = new
             * ServiceRegistryBuilder().applySettings(configuration
             * .getProperties()).buildServiceRegistry(); sessionFactory =
             * configuration.buildSessionFactory(serviceRegistry);
             * 
             * configuration.setSessionFactoryObserver(new
             * SessionFactoryObserver() {
             * 
             * @Override public void sessionFactoryCreated(SessionFactory
             * factory) { }
             * 
             * @Override public void sessionFactoryClosed(SessionFactory
             * factory) { ServiceRegistryBuilder.destroy(serviceRegistry); }
             * });
             */
            sessionFactory = configuration.buildSessionFactory();
            session = sessionFactory.openSession();
            session.doWork(new Work() {
                public void execute(Connection connection) throws SQLException {
                    connection.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
                    connection.setAutoCommit(false);
                }
            });
            session.setFlushMode(FlushMode.ALWAYS);
        } catch (Exception e) {
            e.printStackTrace();
        }
    } else {
        session.clear();
    }
    return session;
}

From source file:com.sos.hibernate.classes.SosHibernateSession.java

License:Apache License

public static Session getInstance(IHibernateOptions options) {
    if (session == null) {
        ClassLoader classLoader = ClassLoader.getSystemClassLoader();
        try {/*from   w  ww.jav  a 2 s.  c o  m*/
            Class dailyScheduleDBItem = classLoader.loadClass("com.sos.dailyschedule.db.DailyScheduleDBItem");
            Class schedulerTaskHistoryDBItem = classLoader
                    .loadClass("com.sos.scheduler.history.db.SchedulerTaskHistoryDBItem");
            Class schedulerOrderStepHistoryDBItem = classLoader
                    .loadClass("com.sos.scheduler.history.db.SchedulerOrderStepHistoryDBItem");
            Class schedulerOrderHistoryDBItem = classLoader
                    .loadClass("com.sos.scheduler.history.db.SchedulerOrderHistoryDBItem");
            Class schedulerInstancesDBItem = classLoader
                    .loadClass("com.sos.scheduler.db.SchedulerInstancesDBItem");
            Class schedulerEventDBItem = classLoader.loadClass("com.sos.eventing.db.SchedulerEventDBItem");

            Class jobNetPlanDBItem = classLoader.loadClass("com.sos.jobnet.db.JobNetPlanDBItem");
            Class jobNetNodeDBItem = classLoader.loadClass("com.sos.jobnet.db.JobNetNodeDBItem");
            Class jobNetEdgesDBItem = classLoader.loadClass("com.sos.jobnet.db.JobNetEdgesDBItem");

            Class eventsDBItem = classLoader.loadClass("com.sos.Jobnet.db.EventsDBItem");

            Class jobNetHistoryDBItem = classLoader.loadClass("com.sos.jobnet.db.JobNetHistoryDBItem");
            Class jobNetCmdHistoryDBItem = classLoader.loadClass("com.sos.jobnet.db.JobNetCmdHistoryDBItem");
            Class jobNetDBItem = classLoader.loadClass("com.sos.jobnet.db.JobNetDBItem");

            // Configuration configuration = new Configuration();
            Configuration configuration = new Configuration().addAnnotatedClass(dailyScheduleDBItem)
                    .addAnnotatedClass(schedulerTaskHistoryDBItem)
                    .addAnnotatedClass(schedulerOrderStepHistoryDBItem)
                    .addAnnotatedClass(schedulerOrderHistoryDBItem).addAnnotatedClass(schedulerInstancesDBItem)
                    .addAnnotatedClass(jobNetPlanDBItem).addAnnotatedClass(jobNetNodeDBItem)
                    .addAnnotatedClass(jobNetEdgesDBItem).addAnnotatedClass(schedulerEventDBItem);
            configuration.setProperty("hibernate.connection.url",
                    options.gethibernate_connection_url().Value());
            configuration.setProperty("hibernate.connection.password",
                    options.gethibernate_connection_password().Value());
            configuration.setProperty("hibernate.connection.url",
                    options.gethibernate_connection_url().Value());
            configuration.setProperty("hibernate.connection.username",
                    options.gethibernate_connection_username().Value());
            configuration.setProperty("hibernate.dialect", options.gethibernate_dialect().Value());
            configuration.setProperty("hibernate.show_sql", options.gethibernate_show_sql().Value());
            configuration.setProperty("hibernate.connection.autocommit",
                    options.gethibernate_connection_autocommit().Value());
            configuration.setProperty("hibernate.format_sql", options.gethibernate_format_sql().Value());
            sessionFactory = configuration.buildSessionFactory();
            session = sessionFactory.openSession();
            session.setFlushMode(FlushMode.ALWAYS);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    } else {
        session.clear();
    }
    return session;
}

From source file:com.syntelinc.BOK.ATM.transactionpkg.HibernateTransaction.java

private void AccountTrans(Transaction tran) throws IllegalArgumentException {
    Configuration cfg = new Configuration().configure();
    SessionFactory sf = cfg.buildSessionFactory();
    Session s = sf.openSession();//from   w ww  .  j a  v a 2s .  co m
    org.hibernate.Transaction t = s.beginTransaction();

    SQLQuery q;
    if (sessionMap.get("accounttype").equals("checking")) {
        tran = new CheckingTransaction();
        q = s.createSQLQuery("select balance from checkingtrans where acctid=?");
    } else {
        tran = new SavingsTransaction();
        q = s.createSQLQuery("select balance from savingtrans where acctid=?");
    }

    tran.setAcctid(Integer.parseInt((String) sessionMap.get("accountid")));

    q.setInteger(0, tran.getAcctid());
    List ld = q.list();
    BigDecimal bal;
    if (ld.isEmpty())
        bal = new BigDecimal(0);
    else
        bal = (BigDecimal) ld.get(ld.size() - 1);

    tran.setTime(new Date());
    tran.setLocation("1234 North Vegas Street");
    DecimalFormat df = new DecimalFormat("#.##");
    df.setRoundingMode(RoundingMode.CEILING);
    tran.setDebitamt(Double.parseDouble((String) sessionMap.get("depositamt")));
    tran.setDebitamt(Double.parseDouble(df.format(tran.getDebitamt())));
    tran.setCreditamt(Double.parseDouble((String) sessionMap.get("withdrawamt")));
    tran.setCreditamt(Double.parseDouble(df.format(tran.getCreditamt())));
    switch ((String) sessionMap.get("type")) {
    case "cash":
        tran.setType(1);
        tran.setBalance(bal.doubleValue() + tran.getDebitamt() - tran.getCreditamt());
        tran.setBalance(Double.parseDouble(df.format(tran.getBalance())));
        break;
    case "check":
        tran.setType(2);
        tran.setBalance(bal.doubleValue());
        tran.setBalance(Double.parseDouble(df.format(tran.getBalance())));
        break;
    case "default":
        throw new IllegalArgumentException();
    }
    sessionMap.put("balance", tran.getBalance());

    s.save(tran);
    t.commit();

    s.close();
    sf.close();
}

From source file:com.syntelinc.BOK.ATM.withdrawpkg.CheckDailyLimit.java

public double getCurrentTotal(int accountid) {
    Configuration cfg = new Configuration().configure();
    SessionFactory sf = cfg.buildSessionFactory();
    Session s = sf.openSession();/*from   www.ja va 2s  . co  m*/
    org.hibernate.Transaction t = s.beginTransaction();
    SQLQuery q;
    q = s.createSQLQuery("select creditamt from checkingtrans where acctid=? AND TIME < ? AND TIME > ?");
    q.setInteger(0, accountid);
    q.setTimestamp(1, getDayEnd());
    q.setTimestamp(2, getDayStart());
    List<BigDecimal> li = q.list();
    double totalCredit = 0;
    if (li.isEmpty())
        totalCredit = 0;
    else if (li.get(0) == null)
        totalCredit = 0;
    else {
        for (BigDecimal cred : li) {
            totalCredit += cred.doubleValue();
        }
    }

    System.out.println(totalCredit);

    if (!li.isEmpty())
        return totalCredit;
    else
        return 0;
}

From source file:com.thesett.catalogue.config.HibernateConfigBean.java

License:Apache License

/**
 * Creates a hibernate session factory from a set of properties.
 *
 * @param  configProperties The properties.
 *
 * @return A hibernate session factory.// www.jav a2s .  c  o  m
 *
 * @throws ConfigException If any configuration errors occurr within Hibernate.
 */
private SessionFactory createSessionFactory(Properties configProperties) throws ConfigException {
    SessionFactory sessionFactory;

    try {
        Configuration config = new Configuration().addProperties(configProperties)
                .addResource(getMappingResource());

        // Create the session factory.
        sessionFactory = config.buildSessionFactory();
    } catch (HibernateException e) {
        throw new ConfigException(
                "Hibernate threw an exception during creation of its configuration or the session factory.", e,
                null, null);
    }

    return sessionFactory;
}

From source file:com.trifork.stamdata.persistence.PersistenceModule.java

License:Mozilla Public License

@Provides
@Singleton/* w w w .java2  s.c om*/
protected SessionFactory provideSessionFactory(@Persistent Set<Object> entities,
        @Named(JDBC_URL_PROP) String jdbcURL, @Named(DB_USERNAME_PROP) String username,
        @Nullable @Named(DB_PASSWORD_PROP) String password) {
    Configuration config = new Configuration();

    config.setProperty("hibernate.connection.url", jdbcURL);
    config.setProperty("hibernate.connection.username", username);
    config.setProperty("hibernate.connection.password", password);

    // TODO: These can be configurable to e.g. allow in-memory databases.

    config.setProperty("hibernate.connection.driver_class", "com.mysql.jdbc.Driver");
    config.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQLInnoDBDialect");

    config.setProperty("hibernate.connection.characterEncoding", "utf8");

    // Set the default behavior of dates fetched from the database to be
    // converted to null. The alternative 00-00-0000 or similar is strange.

    config.setProperty("hibernate.connection.zeroDateTimeBehavior", "convertToNull");

    config.setProperty("hibernate.transaction.factory_class",
            "org.hibernate.transaction.JDBCTransactionFactory");
    config.setProperty("hibernate.current_session_context_class", "thread");

    // TODO: Look into caching.

    config.setProperty("hibernate.cache.provider_class", "org.hibernate.cache.NoCacheProvider");

    // Since we are not using the exact same version as provided
    // on JBoss we need to disable search and validator registration.
    //
    // If we don't do this Hibernate will use the provided version
    // of search and validator which do not match the ones in the war.

    config.setProperty("hibernate.validator.autoregister_listeners", "false");
    config.setProperty("hibernate.search.autoregister_listeners", "false");

    // Use a C3P0 connection pool.
    // The default connection pool is not meant for production use.
    //
    // TODO: Make this configurable.

    config.setProperty("hibernate.c3p0.min_size", "5");
    config.setProperty("hibernate.c3p0.max_size", "100");
    config.setProperty("hibernate.c3p0.timeout", "200");

    // See debug information
    //        config.setProperty("hibernate.c3p0.unreturnedConnectionTimeout", "2");
    //        config.setProperty("hibernate.c3p0.debugUnreturnedConnectionStackTraces", "true");

    // Lastly register all the entities.

    for (Object entity : entities) {
        config.addAnnotatedClass(entity.getClass());
    }

    return config.buildSessionFactory();
}