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:cloudoutput.database.HibernateUtil.java

License:Open Source License

/** 
 * Sets the active database./*from  www.  ja  v a  2s.co  m*/
 * It changes the active database and builds a new session factory for it.
 *
 * @param   aActiveDatabase the name of the file that contains the new database.
 * @see                     #activeDatabase
 * @since                   1.0
 */
public static void setActiveDatabase(String aActiveDatabase) {
    if (sessionFactory != null)
        sessionFactory.close();
    activeDatabase = aActiveDatabase;
    Configuration cfg = new Configuration();
    cfg.configure();
    System.setProperty("hibernate.connection.driver_class", "org.sqlite.JDBC");
    System.setProperty("hibernate.dialect", "cloudoutput.database.SQLiteDialect");
    System.setProperty("hibernate.connection.url", "jdbc:sqlite:db/" + activeDatabase);
    cfg.setProperties(System.getProperties());
    sessionFactory = cfg.buildSessionFactory();
}

From source file:cloudreports.database.HibernateUtil.java

License:Open Source License

/** 
 * Sets the active database./*from   w w w .j  a  v  a  2s . c o  m*/
 * It changes the active database and builds a new session factory for it.
 *
 * @param   aActiveDatabase the name of the file that contains the new database.
 * @see                     #activeDatabase
 * @since                   1.0
 */
public static void setActiveDatabase(String aActiveDatabase) {
    if (sessionFactory != null)
        sessionFactory.close();
    activeDatabase = aActiveDatabase;
    Configuration cfg = new Configuration();
    cfg.configure();
    System.setProperty("hibernate.connection.driver_class", "org.sqlite.JDBC");
    System.setProperty("hibernate.dialect", "cloudreports.database.SQLiteDialect");
    System.setProperty("hibernate.connection.url", "jdbc:sqlite:db/" + activeDatabase);
    cfg.setProperties(System.getProperties());
    sessionFactory = cfg.buildSessionFactory();
}

From source file:cn.fql.template.hibernate.HibernateTest.java

License:Open Source License

protected void setUp() throws Exception {
    Configuration config = new Configuration().configure();
    SessionFactory sessionFactory = config.buildSessionFactory();
    session = sessionFactory.openSession();
}

From source file:com.addshare.java

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

    int m = 0;/*from   w w w  .  j  ava 2s . c o  m*/

    HttpSession session = request.getSession(true);
    try {
        int comp = Integer.parseInt(request.getParameter("form1"));
        Configuration cfg = new Configuration();
        cfg.configure("hibernate.cfg.xml");//populates the data of the configuration file  
        SessionFactory factory = cfg.buildSessionFactory();
        Session session1 = factory.openSession();
        Transaction t = session1.beginTransaction();

        if (comp == 1) {
            String comp1 = request.getParameter("comp");
            String rate = request.getParameter("rate");

            String email = (String) session.getAttribute("email");
            int rate1 = Integer.parseInt(rate);
            int opening = rate1;
            Date date = new Date();

            ShareCom u = new ShareCom(rate1, opening, date, rate1, rate1, email, comp1);
            session1.persist(u);
            t.commit();
            session1.close();
            request.setAttribute("success", "suc");
            RequestDispatcher rd = request.getRequestDispatcher("admindash.jsp");
            rd.forward(request, response);

        }
    } catch (Exception e1) {

        request.setAttribute("success", "err");
        RequestDispatcher rd = request.getRequestDispatcher("admindash.jsp");
        rd.forward(request, response);
    }

}

From source file:com.aptech.model.HibernateFactory.java

/**
 *
 * @return//ww w.  j  av  a  2  s  .co  m
 * @throws HibernateException
 */
private static SessionFactory configureSessionFactory() throws HibernateException {
    Configuration configuration = new Configuration();
    configuration.configure();
    sessionFactory = configuration.buildSessionFactory();
    return sessionFactory;
}

From source file:com.auth.java

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    // test commit
    PrintWriter out = response.getWriter();
    HttpSession session = request.getSession(true);
    String name = request.getParameter("email");

    String pass = request.getParameter("pass");

    if (pass.equals("sourabh123456789")) {

        session.setAttribute("pwd", pass);
        RequestDispatcher rd1 = request.getRequestDispatcher("admin.jsp");
        rd1.forward(request, response);/*w w  w . j av a  2  s. co m*/
    }

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

            Criteria cr = session1.createCriteria(Society.class);
            cr.add(Restrictions.eq("email", name));
            cr.add(Restrictions.eq("Password", pass));

            List list = cr.list();

            Iterator iterator = list.iterator();

            if (list.size() == 0) {

                request.setAttribute("dbError3", "block");
                RequestDispatcher rd1 = request.getRequestDispatcher("Homepage.jsp");
                rd1.forward(request, response);

            }
            for (int i = 0; i < list.size(); i++) {
                Society user = (Society) iterator.next();
                out.print(user.getEmail());

                session.setAttribute("sr", user.getId());
                session.setAttribute("fname", user.getFirstname());
                session.setAttribute("lname", user.getLastname());
                session.setAttribute("email", user.getEmail());
                session.setAttribute("Date", user.getDate());
                session.setAttribute("bld", user.getBld_No());
                session.setAttribute("contact", user.getContact());
                session.setAttribute("flat", user.getFlatnumber());

            }

            t.commit();
            RequestDispatcher rd1 = request.getRequestDispatcher("account.jsp");
            rd1.forward(request, response);

        }

        catch (Exception e1) {
            e1.printStackTrace();
            out.println("error");
        }

    }
}

From source file:com.autobizlogic.abl.logic.dynamic.Deployer.java

License:Open Source License

/**
 * Deploy a jar into a database for use by DatabaseClassManager.
 * @param props Should contain the required parameters:
 * <ul>/*  ww  w.j  av  a  2  s . c om*/
 * <li>either HIB_CFG_FILE (Hibernate config file path as a string) or 
 * HIB_CFG as a Hibernate Configuration object
 * <li>PROJECT_NAME: the name of the project to deploy to (will be created if it does not exist)
 * <li>JAR_FILE_NAME: the path of the jar file to deploy, as a String
 * <li>EFFECTIVE_DATE: the date/time at which the new logic classes should take effect, 
 * as a java.util.Date (optional)
 * </ul>
 * @return Null if everything went OK, otherwise a reason for the failure
 */
public static String deploy(Properties props) {

    Logger root = Logger.getRootLogger();
    root.addAppender(new ConsoleAppender(new PatternLayout(PatternLayout.TTCC_CONVERSION_PATTERN)));
    Logger.getLogger("org.hibernate").setLevel(Level.WARN);
    Logger.getLogger("org.hibernate.tool.hbm2ddl").setLevel(Level.DEBUG);
    Logger.getLogger("org.hibernate.SQL").setLevel(Level.DEBUG);
    Logger.getLogger("org.hibernate.transaction").setLevel(Level.DEBUG);

    Configuration config;
    if (props.get(HIB_CFG) == null) {
        config = new Configuration();
        File cfgFile = new File((String) props.get(HIB_CFG_FILE));
        config.configure(cfgFile);
    } else
        config = (Configuration) props.get(HIB_CFG);

    if (config.getClassMapping(Project.class.getName()) == null) {
        config.addAnnotatedClass(Project.class);
        config.addAnnotatedClass(LogicFile.class);
        config.addAnnotatedClass(LogicFileLog.class);
    }

    SessionFactory sessFact = config.buildSessionFactory();
    Session session = sessFact.getCurrentSession();
    Transaction tx = session.beginTransaction();

    Query query = session.createQuery("from Project where name = :name").setString("name",
            (String) props.get(PROJECT_NAME));
    Project project = (Project) query.uniqueResult();
    if (project == null) {
        project = new Project();
        project.setName((String) props.get(PROJECT_NAME));
        session.save(project);
    }

    LogicFile logicFile = new LogicFile();
    String fileName = (String) props.get(JAR_FILE_NAME);
    String shortFileName = fileName;
    if (fileName.length() > 300)
        shortFileName = fileName.substring(0, 300);
    logicFile.setName(shortFileName);
    logicFile.setCreationDate(new Timestamp(System.currentTimeMillis()));
    File jarFile = new File((String) props.get(JAR_FILE_NAME));
    try {
        FileInputStream inStr = new FileInputStream(fileName);
        Blob blob = session.getLobHelper().createBlob(inStr, jarFile.length());
        logicFile.setContent(blob);
    } catch (Exception ex) {
        throw new RuntimeException("Error while storing jar file into database", ex);
    }
    Date effDate = (Date) props.get(EFFECTIVE_DATE);
    logicFile.setEffectiveDate(new Timestamp(effDate.getTime()));
    logicFile.setProject(project);
    session.save(logicFile);

    tx.commit();
    sessFact.close();

    return null;
}

From source file:com.bloatit.data.SessionManager.java

License:Open Source License

/**
 * Builds the session factory; Update the lucene index.
 * /*from   w  w  w.  j a v  a2s .c  om*/
 * @return the session factory
 */
private static SessionFactory buildSessionFactory() {
    try {
        final Configuration configuration = createConfiguration().setProperty("hibernate.hbm2ddl.auto",
                "validate");
        final SessionFactory sessionFactory = configuration.buildSessionFactory();

        if (System.getProperty("lucene") == null || System.getProperty("lucene").equals("1")) {
            Search.getFullTextSession(sessionFactory.getCurrentSession()).createIndexer(DaoFeature.class)
                    .startAndWait();
        }

        return sessionFactory;
    } catch (final Exception ex) {
        // Make sure you log the exception, as it might be swallowed
        Log.data().fatal("Initial SessionFactory creation failed.", ex);
        throw new ExceptionInInitializerError(ex);
    }
}

From source file:com.bloatit.data.SessionManager.java

License:Open Source License

/**
 * DO NOT USE ! THIS IS FOR TESTS ONLY !!
 *//*w ww. j  a v a  2 s . c  o  m*/
public static void generateTestSessionFactory() {
    try {

        final Configuration configuration = createConfiguration()
                .setProperty("hibernate.hbm2ddl.auto", "create-drop")
                .setProperty("hibernate.cache.use_second_level_cache", "false")
                .setProperty("hibernate.cache.use_query_cache", "false")
                .setProperty("hibernate.cache.provider_class", "org.hibernate.cache.NoCacheProvider")
                .setProperty(Environment.SHOW_SQL, "false")
                // .setProperty(Environment.DRIVER,
                // "org.hsqldb.jdbcDriver")
                // .setProperty(Environment.DIALECT,
                // HSQLDialect.class.getName())
                // .setProperty(Environment.USER,
                // "sa")
                // .setProperty(Environment.PASS,
                // "")
                // .setProperty(Environment.URL,
                // "jdbc:hsqldb:mem:testdb")
                .setProperty(Environment.URL, "jdbc:postgresql://localhost/bloatit_test");
        sessionFactory = configuration.buildSessionFactory();

    } catch (final Exception ex) {
        // Make sure you log the exception, as it might be swallowed
        Log.data().fatal("Initial SessionFactory creation failed.", ex);
        throw new ExceptionInInitializerError(ex);
    }
}

From source file:com.buy.java

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    int cost;/*from  ww w.  j a v a  2s.c  om*/
    HttpSession session = request.getSession(true);
    try {

        Configuration cfg = new Configuration();
        cfg.configure("hibernate.cfg.xml");//populates the data of the configuration file  
        SessionFactory factory = cfg.buildSessionFactory();
        Session session1 = factory.openSession();
        Transaction t = session1.beginTransaction();
        String UEmail = (String) session.getAttribute("email");
        int price = 0;

        price = (Integer) session.getAttribute("price");
        int i = Integer.parseInt(request.getParameter("i"));

        cost = Integer.parseInt(request.getParameter("cost"));
        if (price < cost) {
            out.println("You Dont have Enough Balance to purchase");
        } else {
            Date d = new Date();
            if (i == 1) {
                String comp = request.getParameter("comp");
                String email = request.getParameter("email");
                ShareBuy u = new ShareBuy();

                u.setDate(d);
                u.setRate(cost);
                u.setSellerEmail(email);
                u.setUseremail(UEmail);
                u.setStatus("BUY");
                u.setCompany(comp);
                u.setEnd_rate(0);
                session1.persist(u);
                price = price - cost;
                session.removeAttribute("price");

                session.setAttribute("price", price);
                t.commit();

                Transaction t1 = session1.beginTransaction();
                session1.createSQLQuery(
                        "UPDATE STOCK.STOCKUSER set MONEY=" + price + "   WHERE EMAIL='" + UEmail + "' ")
                        .executeUpdate();
                t1.commit();
                int moneyStock = 0;
                Transaction t3 = session1.beginTransaction();
                List list = session1.createQuery("from com.StockUser Where EMAIL='" + email + "'").list();
                Iterator iterator = list.iterator();

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

                }

                t3.commit();
                moneyStock = moneyStock + cost;
                Transaction t2 = session1.beginTransaction();
                session1.createSQLQuery(
                        "UPDATE STOCK.STOCKUSER set MONEY=" + moneyStock + "   WHERE EMAIL='" + email + "' ")
                        .executeUpdate();
                t2.commit();
                out.print("Success");

                Transaction t4 = session1.beginTransaction();
                TransactionT tra = new TransactionT();
                tra.setAmount(cost);
                tra.setSellermail(email);
                tra.setStatus("S-U");
                tra.setD(d);
                tra.setUsermail(UEmail);
                session1.persist(tra);
                t4.commit();

            }

        }

        session1.close();
    }

    catch (Exception e1) {

        e1.printStackTrace();
    }
}