Example usage for org.hibernate Session get

List of usage examples for org.hibernate Session get

Introduction

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

Prototype

Object get(String entityName, Serializable id);

Source Link

Document

Return the persistent instance of the given named entity with the given identifier, or null if there is no such persistent instance.

Usage

From source file:carregaEstrela.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//w w w.java 2  s .c om
 *
 * @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");
    try (PrintWriter out = response.getWriter()) {
        /* TODO output your page here. You may use following sample code. */

        Integer idEstrela;

        if (request.getParameter("chave") == null || request.getParameter("chave").equals("")) {
            out.println("Favor informar um id");
        } else {

            idEstrela = Integer.parseInt(request.getParameter("chave"));

            try {

                Estrela estrela;

                Session sessao = HibernateUtil.getSessionFactory().openSession();

                estrela = (Estrela) sessao.get(Estrela.class, idEstrela);

                if (estrela == null) {
                    out.println("Nao encontrei a estrela de id: " + idEstrela);
                } else {

                    out.println("ID:" + idEstrela + " ");
                    out.println("Nome:" + estrela.getNome());
                    out.println("Constelao:" + estrela.getConstelacao());
                    out.println("Distancia da Terra: " + estrela.getDistancia_da_Terra());
                }
            } catch (Exception ex) {
                out.println("Erro ao buscar estrela: " + ex.getMessage());
            }
        }

    }
}

From source file:view_pat_profile_byLab.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*  w  ww.  j  a  va  2  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 = HibernateUtil.getSessionFactory();
        Session ss1 = sf.getCurrentSession();
        Transaction tr1 = ss1.beginTransaction();
        HttpSession hs = request.getSession();

        if (hs.getAttribute("lab") != null) {

            if (request.getParameter("pid") != null) {

                int p_id = Integer.parseInt(request.getParameter("pid"));
                Patient p = (Patient) ss1.get(Patient.class, p_id);
                request.setAttribute("pdata", p);

                RequestDispatcher rd = request.getRequestDispatcher("viewpatprof_byLab.jsp");
                rd.forward(request, response);

            }

        }

    }

    catch (HibernateException he) {
        he.getMessage();
    }

    finally {

        out.close();
    }
}

From source file:view_labprofile_admin.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*w w w.  j  a  va  2 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 = HibernateUtil.getSessionFactory();
        Session ss1 = sf.getCurrentSession();
        Transaction tr1 = ss1.beginTransaction();
        HttpSession hs = request.getSession();

        if (hs.getAttribute("admin") != null) {
            if (request.getParameter("lid") != null) {

                int l_id = Integer.parseInt(request.getParameter("lid"));
                Lab d = (Lab) ss1.get(Lab.class, l_id);
                request.setAttribute("ldata", d);

                RequestDispatcher rd = request.getRequestDispatcher("view_labprofile_admin.jsp");
                rd.forward(request, response);

            }

        } else {
            RequestDispatcher rd = request.getRequestDispatcher("login.jsp");
            rd.forward(request, response);

        }

    }

    catch (HibernateException he) {
        he.getMessage();
    }

    finally {

        out.close();
    }
}

From source file:StudentJUnitTest.java

@Test
public void updateStudentInDB() {
    Session session = sessionFctry.openSession();
    Transaction tx = null;//from   w w w .j  a  v a2  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:StudentJUnitTest.java

@Test
public void usuwanieStudenta() {
    Session session = sessionFctry.openSession();
    Transaction tx = null;/*from w w w.  j a va 2  s  . co  m*/
    Integer idTemporaryStudent = null;

    /***********************/
    /*dodaj studenta do db*/
    /**********************/
    tx = session.beginTransaction();

    Student temporaryStudent = new Student("Karol", "Marzyciel", "Malinowa 23");
    idTemporaryStudent = (Integer) session.save(temporaryStudent);

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

    /****************************/
    /*usu nowododanego studenta*/
    /****************************/
    session = sessionFctry.openSession();
    tx = session.beginTransaction();
    try {
        Student usuwany = (Student) session.get(Student.class, idTemporaryStudent);
        session.delete(usuwany);

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

        session.close();
    }

    /******************************/
    /*sprbuj pobra tego studenta*/
    /******************************/
    session = sessionFctry.openSession();
    tx = session.beginTransaction();

    Student poszukiwany = (Student) session.get(Student.class, idTemporaryStudent); //to powinno wyrzuci wyjtek

    assertNull(poszukiwany);

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

}

From source file:systemgen_report_doc.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from  ww  w.j  a  va 2s .  com*/
 *
 * @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 {
        /* TODO output your page here. You may use following sample code. */

        SessionFactory sf = HibernateUtil.getSessionFactory();
        Session ss = sf.openSession();
        Transaction tr = ss.beginTransaction();
        HttpSession hs = request.getSession();

        if (hs.getAttribute("doctor") != null) {
            Patient p1 = (Patient) hs.getAttribute("patient");
            if (request.getParameter("calcid") != null) {

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

                Calculationmeteredata cm1 = (Calculationmeteredata) ss.get(Calculationmeteredata.class, calcid);
                String color = "red";

                if (cm1.getCalculationmeteredataId() != null) {

                    String gender = "MALE";
                    Criteria optcr = ss.createCriteria(PatientfactorAnswer.class);
                    optcr.add(Restrictions.eq("calculationmeteredataId", cm1));
                    ArrayList<PatientfactorAnswer> anslist = (ArrayList<PatientfactorAnswer>) optcr.list();
                    if (anslist.size() > 0) {

                        FactorOption agefac = new FactorOption();
                        for (PatientfactorAnswer opp : anslist) {
                            if (opp.getFactorId().equals(new FactorDetails(1))) {
                                if (opp.getFactorOptionId().getFoptionId().equals(16)) {
                                    gender = "FEMALE";
                                }
                                System.out.println("Gender is :" + gender + opp.getFactorOptionId());
                            }
                            if (opp.getFactorId().equals(new FactorDetails(2))) {
                                agefac = opp.getFactorOptionId();
                                System.out.println("Age is :" + agefac.getFactorOption());
                            }
                        }
                        if (gender.equals("MALE")) {
                            //                        Set Chart Data   
                            String[] chartdata = new String[4];
                            String[] rchartdata = new String[4];

                            Criteria cr01 = ss.createCriteria(AbsulateRiskMale.class);
                            cr01.add(Restrictions.eq("foptionid", agefac));
                            cr01.setProjection(Projections.max("green"));
                            if (cr01.uniqueResult() != null) {
                                chartdata[0] = cr01.uniqueResult().toString();
                                int cdata = Integer.parseInt(chartdata[0]);
                                if (cdata >= cm1.getMetervalue()) {
                                    color = "green";
                                }
                            }
                            Criteria cr02 = ss.createCriteria(AbsulateRiskMale.class);
                            cr02.add(Restrictions.eq("foptionid", agefac));
                            cr02.setProjection(Projections.max("violet"));
                            if (cr02.uniqueResult() != null) {
                                chartdata[1] = cr02.uniqueResult().toString();
                                int cdata = Integer.parseInt(chartdata[1]);
                                if (cdata >= cm1.getMetervalue()) {
                                    color = "violet";
                                }
                            }
                            System.out.println(chartdata[1]);
                            System.out.println(color);
                            Criteria cr03 = ss.createCriteria(AbsulateRiskMale.class);
                            cr03.add(Restrictions.eq("foptionid", agefac));
                            cr03.setProjection(Projections.max("yellow"));
                            if (cr03.uniqueResult() != null) {
                                chartdata[2] = cr03.uniqueResult().toString();
                                int cdata = Integer.parseInt(chartdata[2]);
                                if (cdata >= cm1.getMetervalue()) {
                                    color = "yellow";
                                }
                            }
                            chartdata[3] = "54";

                            //                                RchartData create
                            Criteria cr010 = ss.createCriteria(AbsulateRiskMale.class);
                            cr010.add(Restrictions.eq("foptionid", agefac));
                            cr010.setProjection(Projections.max("rGreen"));
                            if (cr010.uniqueResult() != null) {
                                rchartdata[0] = cr010.uniqueResult().toString();
                            }
                            Criteria cr020 = ss.createCriteria(AbsulateRiskMale.class);
                            cr020.add(Restrictions.eq("foptionid", agefac));
                            cr020.setProjection(Projections.max("rViolet"));
                            if (cr020.uniqueResult() != null) {
                                rchartdata[1] = cr020.uniqueResult().toString();

                            }
                            System.out.println(chartdata[1]);
                            System.out.println(color);
                            Criteria cr030 = ss.createCriteria(AbsulateRiskMale.class);
                            cr030.add(Restrictions.eq("foptionid", agefac));
                            cr030.setProjection(Projections.max("rYellow"));
                            if (cr030.uniqueResult() != null) {
                                rchartdata[2] = cr030.uniqueResult().toString();

                            }
                            rchartdata[3] = "30";

                            request.setAttribute("rchartdata", rchartdata);
                            request.setAttribute("chartdata", chartdata);

                        } else if (gender.equals("FEMALE")) {
                            //                        Set Chart Data   
                            String[] chartdata = new String[4];
                            String[] rchartdata = new String[4];

                            Criteria cr01 = ss.createCriteria(AbsoluteRiskFemale.class);
                            cr01.add(Restrictions.eq("foptionid", agefac));
                            cr01.setProjection(Projections.max("green"));
                            if (cr01.uniqueResult() != null) {
                                chartdata[0] = cr01.uniqueResult().toString();
                                int cdata = Integer.parseInt(chartdata[0]);
                                if (cdata >= cm1.getMetervalue()) {
                                    color = "green";
                                }
                            }
                            Criteria cr02 = ss.createCriteria(AbsoluteRiskFemale.class);
                            cr02.add(Restrictions.eq("foptionid", agefac));
                            cr02.setProjection(Projections.max("violet"));
                            if (cr02.uniqueResult() != null) {
                                chartdata[1] = cr02.uniqueResult().toString();
                                int cdata = Integer.parseInt(chartdata[1]);
                                if (cdata >= cm1.getMetervalue()) {
                                    color = "violet";
                                }
                            }
                            Criteria cr03 = ss.createCriteria(AbsoluteRiskFemale.class);
                            cr03.add(Restrictions.eq("foptionid", agefac));
                            cr03.setProjection(Projections.max("yellow"));
                            if (cr03.uniqueResult() != null) {
                                chartdata[2] = cr03.uniqueResult().toString();
                                int cdata = Integer.parseInt(chartdata[2]);
                                if (cdata >= cm1.getMetervalue()) {
                                    color = "yellow";
                                }
                            }
                            chartdata[3] = "30";

                            //                                RchartData create
                            Criteria cr010 = ss.createCriteria(AbsoluteRiskFemale.class);
                            cr010.add(Restrictions.eq("foptionid", agefac));
                            cr010.setProjection(Projections.max("rGreen"));
                            if (cr010.uniqueResult() != null) {
                                rchartdata[0] = cr010.uniqueResult().toString();
                            }
                            Criteria cr020 = ss.createCriteria(AbsoluteRiskFemale.class);
                            cr020.add(Restrictions.eq("foptionid", agefac));
                            cr020.setProjection(Projections.max("rViolet"));
                            if (cr020.uniqueResult() != null) {
                                rchartdata[1] = cr020.uniqueResult().toString();

                            }
                            System.out.println(chartdata[1]);
                            System.out.println(color);
                            Criteria cr030 = ss.createCriteria(AbsoluteRiskFemale.class);
                            cr030.add(Restrictions.eq("foptionid", agefac));
                            cr030.setProjection(Projections.max("rYellow"));
                            if (cr030.uniqueResult() != null) {
                                rchartdata[2] = cr030.uniqueResult().toString();

                            }
                            rchartdata[3] = "20";

                            request.setAttribute("rchartdata", rchartdata);
                            request.setAttribute("chartdata", chartdata);
                        }
                        Criteria testcr = ss.createCriteria(TestRecommend.class);
                        testcr.add(Restrictions.eq("color", color));
                        ArrayList<TestRecommend> tlist = (ArrayList<TestRecommend>) testcr.list();
                        if (tlist.size() > 0) {
                            request.setAttribute("testlist", tlist);
                        }

                        request.setAttribute("calcdata", cm1);
                        request.setAttribute("anslist", anslist);
                    }
                }
                tr.commit();
                RequestDispatcher rd = request.getRequestDispatcher("doctor_view_systemreport_full.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:CarregaIngrediente.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from   w w w. j  a  v a2s  .c om*/
 *
 * @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");
    try (PrintWriter out = response.getWriter()) {
        /* TODO output your page here. You may use following sample code. */

        Integer idIngrediente;

        if (request.getParameter("chave") == null || request.getParameter("chave").equals("")) {
            out.println("Favor informar um id");
        } else {

            idIngrediente = Integer.parseInt(request.getParameter("chave"));

            try {

                Ingrediente ingrediente;

                Session sessao = HibernateUtil.getSessionFactory().openSession();

                ingrediente = (Ingrediente) sessao.get(Ingrediente.class, idIngrediente);

                if (ingrediente == null) {
                    out.println("Nao encontrei o ingrediente de id: " + idIngrediente);
                } else {

                    out.println("Dados do Ingrediente :" + idIngrediente + " ");
                    out.println("Nome:" + ingrediente.getNome());
                    out.println("Quantidade: " + ingrediente.getQtd());
                    out.println("Valor: " + ingrediente.getValor());
                }
            } catch (Exception ex) {
                out.println("Erro ao buscar ingrediente: " + ex.getMessage());
            }
        }

    }
}

From source file:DbConnectionJUnitTest.java

@Test
public void updateStudentInDB() {
    Session session = sessionFctry.openSession();
    Transaction tx = null;/* w ww  . j a  v a2s  .  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 w w .j  a  v a 2 s  .co  m
    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);
}