Example usage for org.hibernate SessionFactory openSession

List of usage examples for org.hibernate SessionFactory openSession

Introduction

In this page you can find the example usage for org.hibernate SessionFactory openSession.

Prototype

Session openSession() throws HibernateException;

Source Link

Document

Open a Session .

Usage

From source file:com.akursat.ws.UserServiceImpl.java

@Override
public void updateUser(String username, String email) {
    Transaction trns = null;/*from ww  w.j  av  a 2  s .com*/
    SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
    Session session = sessionFactory.openSession();
    try {
        trns = session.beginTransaction();
        Query query = session
                .createQuery("update Users set email = :email_param where username = :username_param ");
        query.setParameter("email_param", email);
        query.setParameter("username_param", username);
        int result = query.executeUpdate();
        session.getTransaction().commit();
        System.out.println((result == 1 ? "User updated." : "Fail!"));
    } catch (RuntimeException e) {
        if (trns != null) {
            trns.rollback();
        }
        e.printStackTrace();
    } finally {
        session.flush();
        session.close();
    }
}

From source file:com.altcolorlab.simplehibernategui.FXMLController.java

@Override
public void initialize(URL location, ResourceBundle resources) {

    //Setting up each column and then population the column with the desired data
    ID.setCellValueFactory(new PropertyValueFactory<Employee, Integer>("id"));
    fNameCol.setCellValueFactory(new PropertyValueFactory<Employee, String>("firstName"));
    lNameCol.setCellValueFactory(new PropertyValueFactory<Employee, String>("lastName"));
    salaryCol.setCellValueFactory(new PropertyValueFactory<Employee, Integer>("salary"));
    //instantiating an arraylist      
    data = FXCollections.observableArrayList();
    //getting the initial sessionFactory from HibernateUtil Class
    SessionFactory sf = HibernateUtil.getSessionFactory();
    //opening the session
    Session session = sf.openSession();
    //setting transaction to null
    Transaction tx = null;/*from   w ww.  j  a  va2 s. c o  m*/
    try {
        //starting the transaction 
        tx = session.beginTransaction();
        //creating a list and querying from the POJO
        List employees = session.createQuery("FROM Employee").list();
        //iterating over the database
        for (Iterator iterator = employees.iterator(); iterator.hasNext();) {

            Employee employee = (Employee) iterator.next();
            data.add(employee);
        }
        tx.commit();
    } catch (HibernateException e) {
        if (tx != null)
            tx.rollback();
        e.printStackTrace();
    } finally {
        //closing session
        session.close();
        //adding the data to the table
        tableview.setItems(data);
    }
}

From source file:com.altcolorlab.simplehibernategui.FXMLController.java

@FXML
private void handleButtonAction() {
    String firstName = tfFirstName.getText();
    String lastName = tfLastName.getText();
    Integer money = Integer.parseInt(tfSalary.getText());
    Integer employeeId;/*from w  w w .j ava 2 s  .  c  om*/
    ManageEmployee emp1 = new ManageEmployee();
    employeeId = emp1.addEmployee(firstName, lastName, money);
    //Setting up each column and then population the column with the desired data
    ID.setCellValueFactory(new PropertyValueFactory<Employee, Integer>("id"));
    fNameCol.setCellValueFactory(new PropertyValueFactory<Employee, String>("firstName"));
    lNameCol.setCellValueFactory(new PropertyValueFactory<Employee, String>("lastName"));
    salaryCol.setCellValueFactory(new PropertyValueFactory<Employee, Integer>("salary"));
    //instantiating an arraylist      
    data = FXCollections.observableArrayList();
    //getting the initial sessionFactory from HibernateUtil Class
    SessionFactory sf = HibernateUtil.getSessionFactory();
    //opening the session
    Session session = sf.openSession();
    //setting transaction to null
    Transaction tx = null;
    try {
        //starting the transaction 
        tx = session.beginTransaction();
        //creating a list and querying from the POJO
        List employees = session.createQuery("FROM Employee").list();
        //iterating over the database
        for (Iterator iterator = employees.iterator(); iterator.hasNext();) {

            Employee employee = (Employee) iterator.next();
            data.add(employee);
        }
        tx.commit();
    } catch (HibernateException e) {
        if (tx != null)
            tx.rollback();
        e.printStackTrace();
    } finally {
        //closing session
        session.close();
        //adding the data to the table
        tableview.setItems(data);
        //clears text fields    
        tfFirstName.clear();
        tfLastName.clear();
        tfSalary.clear();
    }
}

From source file:com.altcolorlab.simplehibernategui.ManageEmployee.java

public int addEmployee(String fname, String lname, int salary) {
    SessionFactory sf = HibernateUtil.getSessionFactory();
    Session session = sf.openSession();
    Transaction tx = null;//from ww  w.  j a va2s.co  m
    Integer employeeID = null;
    try {
        tx = session.beginTransaction();
        Employee employee = new Employee(fname, lname, salary);
        employeeID = (Integer) session.save(employee);
        tx.commit();
    } catch (HibernateException e) {
        if (tx != null)
            tx.rollback();
        e.printStackTrace();
    } finally {
        session.close();
    }
    return employeeID;
}

From source file:com.altcolorlab.simplehibernategui.ManageEmployee.java

public void updateEmployee(Integer EmployeeID, int salary) {
    SessionFactory sf = HibernateUtil.getSessionFactory();
    Session session = sf.openSession();
    Transaction tx = null;/*from   www. j  a v a 2s.c  o m*/
    try {
        tx = session.beginTransaction();
        Employee employee = (Employee) session.get(Employee.class, EmployeeID);
        employee.setSalary(salary);
        session.update(employee);
        tx.commit();
    } catch (HibernateException e) {
        if (tx != null)
            tx.rollback();
        e.printStackTrace();
    } finally {
        session.close();
    }
}

From source file:com.anyuan.thomweboss.persistence.dao.HibernateDaoTemplate.java

License:Apache License

/**
 * ?hibernatejdbctransaction/*ww  w . j  ava  2 s  . c  om*/
 * @author Thomsen
 * @since Dec 15, 2012 11:20:02 PM
 * @return
 */
public static Transaction getTranscation() {

    Transaction transaction = null;
    try {
        Configuration configuration = new Configuration().configure(); // classpathhibernate.cfg.xml
        ServiceRegistry registry = new ServiceRegistryBuilder().applySettings(configuration.getProperties())
                .buildServiceRegistry();
        SessionFactory sessionFactory = configuration.buildSessionFactory(registry); // hibernate4.0 ?buildSessionFactory()
        //            Session session = sessionFactory.getCurrentSession();
        session = sessionFactory.openSession();
        transaction = session.beginTransaction();
    } catch (HibernateException e) {
        e.printStackTrace();
    }

    if (transaction == null) {
        throw new HibernateException("transaction is null");
    }

    return transaction;

}

From source file:com.anyuan.thomweboss.persistence.hibimpl.user.UserDaoHibImpl.java

License:Apache License

@Override
public List<User> listAll() {

    Configuration config = new Configuration().configure();
    ServiceRegistry registry = new ServiceRegistryBuilder().applySettings(config.getProperties())
            .buildServiceRegistry();/*  w w  w.j a  v a2s. c o m*/
    SessionFactory sessionFactory = config.buildSessionFactory(registry);
    Session session = sessionFactory.openSession();

    String hql = "from User";
    Query query = session.createQuery(hql);
    List<User> listUser = query.list();

    session.close();

    return listUser;
}

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);/*from  ww  w .  jav a2  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.baomidou.hibernateplus.utils.HibernateUtils.java

License:Open Source License

/**
 * ?Session//from ww  w  .j a v a2 s. c  om
 *
 * @param factory
 * @param isCurrent
 *            ??session
 * @return
 */
public static Session getSession(SessionFactory factory, Boolean isCurrent) {
    return isCurrent ? factory.getCurrentSession() : factory.openSession();
}