Example usage for org.hibernate Session update

List of usage examples for org.hibernate Session update

Introduction

In this page you can find the example usage for org.hibernate Session update.

Prototype

void update(Object object);

Source Link

Document

Update the persistent instance with the identifier of the given detached instance.

Usage

From source file:HibernateCoursework.java

public void updateProj(Project project, int days, Employee employeeToBeRemoved, Employee employeeToBeAdded) {

    System.out.println("Update Project");
    Session hibernate = sessionFactory.openSession();
    hibernate.beginTransaction();/*from ww  w .j a va  2  s.co m*/

    System.out.println("*************");

    project.setDays(days);

    List tmpList = project.getEmployees();
    tmpList.remove(employeeToBeRemoved);
    tmpList.add(employeeToBeAdded);

    project.setEmployees(tmpList);

    hibernate.update(project);

    hibernate.getTransaction().commit();
    hibernate.flush();
    hibernate.close();
    System.out.println("***Session closed***");

}

From source file:TestNull.java

public static void main(String[] args) {
    Session ses = utils.HibernateUtils.getSessionFactory().getCurrentSession();
    Staff test = new Staff();
    test.setId(6);/*from   w  w  w  .ja  v  a2  s.  c  o  m*/
    test.setUserName("Employee3");
    test.setPassword("33333333");
    test.setFirstName("fffff");
    ses.beginTransaction();
    ses.update(test);
    ses.getTransaction().commit();
    System.out.println("done");
}

From source file:StudentJUnitTest.java

@Test
public void updateStudentInDB() {
    Session session = sessionFctry.openSession();
    Transaction tx = null;/*from  www .  ja  v a  2 s .  c  o m*/
    String randomAdress = "Wabrszyska 34 m " + ((new Random()).nextInt(100) + 1);

    try {
        tx = session.beginTransaction();

        Student pierwszy = (Student) session.get(Student.class, 1);

        pierwszy.setAdress(randomAdress);

        session.update(pierwszy);

        tx.commit();
    } catch (Exception e) {
        if (tx != null)
            tx.rollback();
        e.printStackTrace();
    } finally {

        session.close();
    }

    //Nowa sesja by sprawdzi czy adres danego studenta zosta zaktualizowany
    session = sessionFctry.openSession();
    tx = null;
    String adresPierwszeoPoAktualizacji = null;

    try {
        tx = session.beginTransaction();

        Student pierwszy = (Student) session.get(Student.class, 1);

        adresPierwszeoPoAktualizacji = pierwszy.getAdress();

        tx.commit();
    } catch (Exception e) {
        if (tx != null)
            tx.rollback();
        e.printStackTrace();
    } finally {

        session.close();
    }

    assertEquals(randomAdress, adresPierwszeoPoAktualizacji);
}

From source file:DbConnectionJUnitTest.java

@Test
public void updateStudentInDB() {
    Session session = sessionFctry.openSession();
    Transaction tx = null;//from   w w  w. j a v  a 2 s. c  o m
    String randomAdress = "Wabrszyska 34 m " + ((new Random()).nextInt(100) + 1);

    try {
        tx = session.beginTransaction();

        Student pierwszy = (Student) session.get(Student.class, 2);

        pierwszy.setAdress(randomAdress);

        session.update(pierwszy);

        tx.commit();
    } catch (Exception e) {
        System.out.println(e);
        if (tx != null)
            tx.rollback();
        e.printStackTrace();
    } finally {

        session.close();
    }

    //Nowa sesja by sprawdzi czy adres danego studenta zosta zaktualizowany
    session = sessionFctry.openSession();
    tx = null;
    String adresPierwszeoPoAktualizacji = null;

    try {
        tx = session.beginTransaction();

        Student pierwszy = (Student) session.get(Student.class, 2);

        adresPierwszeoPoAktualizacji = pierwszy.getAdress();

        tx.commit();
    } catch (Exception e) {
        System.out.println(e);
        if (tx != null)
            tx.rollback();
        e.printStackTrace();
    } finally {

        session.close();
    }
    System.out.println(randomAdress);
    assertEquals(randomAdress, adresPierwszeoPoAktualizacji);
}

From source file:DbConnectionJUnitTest.java

@Test(expected = IllegalArgumentException.class)
public void TestupdateException01() {
    Session session = sessionFctry.openSession();
    Transaction tx = null;/*from   w  ww  .  ja  v a  2  s . c om*/
    String randomAdress = "Wabrszyska 34 m " + ((new Random()).nextInt(100) + 1);

    tx = session.beginTransaction();

    Student pierwszy = (Student) session.get(Student.class, 2);

    pierwszy.setAdress(randomAdress);

    session.update(null);

    tx.commit();
    session.close();

    //Nowa sesja by sprawdzi czy adres danego studenta zosta zaktualizowany
    session = sessionFctry.openSession();
    tx = null;
    String adresPierwszeoPoAktualizacji = null;

    tx = session.beginTransaction();

    pierwszy = (Student) session.get(Student.class, 2);

    adresPierwszeoPoAktualizacji = pierwszy.getAdress();

    tx.commit();
    session.close();
    System.out.println(randomAdress);
    assertEquals(randomAdress, adresPierwszeoPoAktualizacji);
}

From source file:DbConnectionJUnitTest.java

@Test(expected = StaleStateException.class)
public void TestupdateException02() {
    Session session = sessionFctry.openSession();
    Transaction tx = null;/*from  w  w  w.ja v  a2  s  .c  o  m*/
    String randomAdress = "Wabrszyska 34 m " + ((new Random()).nextInt(100) + 1);

    tx = session.beginTransaction();

    Student pierwszy = new Student("Andrzej", "Wajda", "Mietczyska 34 00-242 Krk");

    session.update(pierwszy);

    tx.commit();
    session.close();

    //Nowa sesja by sprawdzi czy adres danego studenta zosta zaktualizowany
    session = sessionFctry.openSession();
    tx = null;
    String adresPierwszeoPoAktualizacji = null;

    tx = session.beginTransaction();

    pierwszy = (Student) session.get(Student.class, 2);

    adresPierwszeoPoAktualizacji = pierwszy.getAdress();

    tx.commit();
    session.close();
    System.out.println(randomAdress);
    assertEquals(randomAdress, adresPierwszeoPoAktualizacji);
}

From source file:admin_add_doctors.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from w ww  . ja v  a 2s  .  c  o m*/
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");

    PrintWriter out = response.getWriter();

    try {
        SessionFactory sf = HibernateUtil.getSessionFactory();
        Session ss = sf.openSession();
        Transaction tr = ss.beginTransaction();
        HttpSession hs = request.getSession();
        if (hs.getAttribute("admin") != null) {
            Admin a = (Admin) hs.getAttribute("admin");

            if (request.getParameter("status") != null && request.getParameter("dId") != null) {

                int apid = Integer.parseInt(request.getParameter("dId"));
                Doctor doc1 = (Doctor) ss.get(Doctor.class, apid);
                if (request.getParameter("status").equals("approve")) {

                    doc1.setStatus("ACTIVE");

                    ss.update(doc1);

                    String subject = "Your Appointment is Approved.!";
                    String content = "Hi, Dr." + doc1.getDFirstname() + " " + doc1.getDLastname() + "\n"
                            + "Your Request has been approved by Admin" + ".\n";
                    String mail = doc1.getEmailId();

                    String[] recipients = new String[] { mail };
                    //String[] bccRecipients = new String[]{"sunilkotadiya777@gmail.com"};  

                    if (new MailUtil().sendMail(recipients, subject, content)) {

                    }
                    request.setAttribute("msg", "Appointment accepted..!");

                } else if (request.getParameter("status").equals("reject")) {
                    doc1.setStatus("REJECTED");
                    ss.update(doc1);
                    String subject = "Your Request is Rejected.!";
                    String content = "Hi, " + doc1.getDFirstname() + " " + doc1.getDLastname()
                            + "Your Request to join Cardiac Countermeasure has been rejected by admin"
                            + ".\n anil ";
                    String mail = doc1.getEmailId();

                    String[] recipients = new String[] { mail };
                    //String[] bccRecipients = new String[]{"sunilkotadiya777@gmail.com"};  

                    if (new MailUtil().sendMail(recipients, subject, content)) {

                    }
                    request.setAttribute("msg", "Appointment rejected..!");
                }

            }

            Criteria cr = ss.createCriteria(Doctor.class);
            //cr.add(Restrictions.eq("dId", a));
            cr.add(Restrictions.eq("status", "not_active"));
            ArrayList<Doctor> da = (ArrayList<Doctor>) cr.list();
            if (da.size() > 0) {
                request.setAttribute("da", da);
            }

            tr.commit();
            RequestDispatcher rd = request.getRequestDispatcher("admin_add_doctors.jsp");
            rd.forward(request, response);
        } else {
            tr.commit();
            RequestDispatcher rd = request.getRequestDispatcher("login.jsp");
            rd.forward(request, response);
        }
    } catch (HibernateException he) {

        out.println(he.getMessage());
    } finally {
        out.close();
    }
}

From source file:agentstatus.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//w w  w  .ja  v a2 s .co m
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    try {
        SessionFactory sf = NewHibernateUtil.getSessionFactory();
        Session ss = sf.openSession();
        Transaction tr = ss.beginTransaction();

        int id = Integer.parseInt(request.getParameter("id"));

        int agentid = Integer.parseInt(request.getParameter("aid"));

        // Touroperator to = (Touroperator)se.get(Touroperator.class, spid);

        AgentDetail ad = (AgentDetail) ss.get(AgentDetail.class, agentid);

        if (id == 0) {
            //Accepted
            out.print(agentid + "accepted");
            AgentDetail ad2 = new AgentDetail();
            ad2.setAAddress1(ad.getAAddress1());
            ad2.setAAddress2(ad.getAAddress2());
            ad2.setAArea(ad.getAArea());
            ad2.setACity(ad.getACity());
            ad2.setACompanyname(ad.getACompanyname());
            ad2.setADescription(ad.getADescription());
            ad2.setAEmail(ad.getAEmail());
            ad2.setAFname(ad.getAFname());
            ad2.setALname(ad.getALname());
            ad2.setAId(ad.getAId());
            ad2.setAImg(ad.getAImg());
            ad2.setANo(ad.getANo());
            ad2.setARating(ad.getARating());
            ad2.setAState(ad.getAState());
            ad2.setUId(ad.getUId());
            ad2.setAWorkx(ad.getAWorkx());
            ad2.setAStatus("Accepted");

            ss.evict(ad);
            ss.update(ad2);
            tr.commit();

        } else if (id == 1) {
            //Denied
            out.print(agentid + "denied");
            ss.delete(ad);
            tr.commit();

        }

    } catch (HibernateException e) {
        out.println(e.getMessage());
    }
}

From source file:accesobd.AccesoRoles.java

License:BSD License

/**
 * Mtodo para actualizar (agregar o modificar) un rol.
 * @param rol La estructura que representa el rol.
 * @param tipoMantenimiento El tipo de mantenimiento (AGREGAR, MODIFICAR, ELIMINAR).
 * @return /*from   ww w  .j a  v a 2s . c  om*/
 */
public Respuesta actualizarRol(AdmRol rol, TipoMantenimiento tipoMantenimiento) {
    Respuesta res = new Respuesta();

    boolean huboError = false;

    Session sesion;
    Transaction tx = null;

    sesion = HibernateUtil.getSessionFactory().openSession();

    // Inicia la transaccin.
    tx = sesion.beginTransaction();
    try {
        String operacionHecha = null;

        if (tipoMantenimiento == TipoMantenimiento.AGREGAR) {
            sesion.save(rol);
            operacionHecha = "agregado";
        } else if (tipoMantenimiento == TipoMantenimiento.MODIFICAR) {
            sesion.update(rol);
            operacionHecha = "modificado";
        } else if (tipoMantenimiento == TipoMantenimiento.ELIMINAR) {
            sesion.delete(rol);
            operacionHecha = "eliminado";
        }

        tx.commit(); // Hace commit a la trasaccin.

        res.setResultado(true);
        res.setMensaje(String.format("Rol %s exitosamente", operacionHecha));
    } catch (Exception ex) {
        huboError = true;

        res.setMensaje("Error al realizar la operacin en base de datos. No se pudo actualizar el sistema.");
        res.setMensajeError(ex.toString());
    } finally {
        if (huboError) {
            tx.rollback();
            res.setResultado(false);
        }
        sesion.close();
    }

    return res;
}

From source file:accesobd.AccesoVistas.java

License:BSD License

/**
 * Mtodo para actualizar (agregar o modificar) una vista.
 * @param vista La estructura que representa el rol.
 * @param tipoMantenimiento El tipo de mantenimiento (AGREGAR, MODIFICAR, ELIMINAR).
 * @return /*from  w  ww  .  java  2s. c om*/
 */
public Respuesta actualizarVista(AdmVista vista, TipoMantenimiento tipoMantenimiento) {
    Respuesta res = new Respuesta();

    boolean huboError = false;

    Session sesion;
    Transaction tx;

    sesion = HibernateUtil.getSessionFactory().openSession();

    // Inicia la transaccin.
    tx = sesion.beginTransaction();
    try {
        String operacionHecha = null;

        if (tipoMantenimiento == TipoMantenimiento.AGREGAR) {
            sesion.save(vista);
            operacionHecha = "agregada";
        } else if (tipoMantenimiento == TipoMantenimiento.MODIFICAR) {
            sesion.update(vista);
            operacionHecha = "modificada";
        } else if (tipoMantenimiento == TipoMantenimiento.ELIMINAR) {
            sesion.delete(vista);
            operacionHecha = "eliminada";
        }

        tx.commit(); // Hace commit a la trasaccin.

        res.setResultado(true);
        res.setMensaje(String.format("Vista %s exitosamente", operacionHecha));
    } catch (Exception ex) {
        huboError = true;

        res.setMensaje("Error al realizar la operacin en base de datos. No se pudo actualizar el sistema.");
        res.setMensajeError(ex.toString());
    } finally {
        if (huboError) {
            tx.rollback();
            res.setResultado(false);
        }
        sesion.close();
    }

    return res;
}