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:TesteSelect.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//  w  ww .  ja  va 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()) {
        Session sessao = HibernateUtil.getSessionFactory().openSession();

        Produto p;
        p = (Produto) sessao.get(Produto.class, "Batata");

        out.println("Produto:" + p.getNome() + " | " + p.getDescricao() + " | " + p.getPreco());

        sessao.close();
    }
}

From source file:CarregaProduto.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.// ww 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");
    try (PrintWriter out = response.getWriter()) {
        /* TODO output your page here. You may use following sample code. */
        int idProduto = 0;

        Produto produto0;

        Session sessao = HibernateUtil.getSessionFactory().openSession();//conectar com o banco

        produto0 = (Produto) sessao.get(Produto.class, idProduto); //select pela chave primaria

        if (produto0 != null) {

            out.println("Dados do pincel 0:");
            out.println("cor:" + produto0.getNome());
            out.println("fabricante: " + produto0.getFabricante());
            //out.println("nume_serie: " + produto0.getId());
            out.println("nume_serie: " + produto0.getIdentificador());
        } else {
            out.println("Nao encontrado o produto " + idProduto);
        }

    }
}

From source file:buscarProfessor.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from ww w.java 2  s  .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");
    try (PrintWriter out = response.getWriter()) {

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

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

        Professor prof = (Professor) sessao.get(Professor.class, nome);

        if (prof != null) {
            out.println("<a href=\"formEditar?nome=" + nome + "\">editar</a>  Professor encontrado: "
                    + prof.getNome() + " " + prof.getSobrenome());

        } else {
            out.println("Nao encontrei professor com nome: " + nome);
        }

    }
}

From source file:lab_view_approved_appointment.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from ww  w.  j  a  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("lab") != null) {
            Lab a = (Lab) hs.getAttribute("lab");

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

                int apid = Integer.parseInt(request.getParameter("appoid"));
                LabAppointment lab1 = (LabAppointment) ss.get(LabAppointment.class, apid);
                if (request.getParameter("status").equals("cancel")) {
                    lab1.setStatus("CANCELLED");
                    ss.update(lab1);
                    request.setAttribute("msg", "Appointment cancelled..!");
                } else if (request.getParameter("status").equals("update")) {
                    //                        doc1.setStatus("CANCELLED");
                    lab1.setDate(request.getParameter("apdate"));
                    lab1.setTime(request.getParameter("aptime"));
                    ss.update(lab1);
                    request.setAttribute("msg", "Appointment Updated..!");
                }

            }

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

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

    }

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

    finally {
        out.close();
    }
}

From source file:doc_view_approved_appointment.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from  w  w  w.  j  av 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("doctor") != null) {
            Doctor a = (Doctor) hs.getAttribute("doctor");

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

                int apid = Integer.parseInt(request.getParameter("appoid"));
                DoctorAppointment doc1 = (DoctorAppointment) ss.get(DoctorAppointment.class, apid);
                if (request.getParameter("status").equals("cancel")) {
                    doc1.setStatus("CANCELLED");
                    ss.update(doc1);

                    String subject = "Appointment Canceled.!";
                    String content = "Hi, " + doc1.getPId().getPFirstname() + " "
                            + "Your appointment has been Canceled by Dr." + doc1.getDId().getDFirstname()
                            + " due to some reasons and we are sorry for that kindly take new appointment ASAP."
                            + ".\n ";
                    String mail = doc1.getPId().getEmailId();

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

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

                    }
                    request.setAttribute("msg", "Appointment cancelled..!");
                } else if (request.getParameter("status").equals("update")) {
                    //                        doc1.setStatus("CANCELLED");
                    doc1.setDate(request.getParameter("apdate"));
                    doc1.setTime(request.getParameter("aptime"));
                    ss.update(doc1);

                    String subject = "Appointment time changed.!";
                    String content = "Hi, " + doc1.getPId().getPFirstname() + " "
                            + "Your appointment has been rescheduled by Dr." + doc1.getDId().getDFirstname()
                            + " due to some reasons kindly note new time" + "  " + "Date : " + doc1.getDate()
                            + "\n" + "Time : " + doc1.getTime() + "\n";
                    String mail = doc1.getPId().getEmailId();

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

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

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

            }

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

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

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

        out.close();
    }
}

From source file:lab_mytest.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from   w ww.  java 2s.  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");
    try (PrintWriter out = response.getWriter()) {
        /* 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("lab") != null) {
            Lab lb = (Lab) hs.getAttribute("lab");

            if (request.getParameter("price") != null && request.getParameter("ltid") != null) {
                int ltid = Integer.parseInt(request.getParameter("ltid"));
                Double price = Double.parseDouble(request.getParameter("price"));
                Labtest lt = (Labtest) ss.get(Labtest.class, ltid);
                lt.setTestFees(price);
                ss.update(lt);
                request.setAttribute("msg", "Test price updated.!");
            }

            Criteria cr = ss.createCriteria(Labtest.class);
            cr.add(Restrictions.eq("lId", lb));
            ArrayList<Labtest> ltest = (ArrayList<Labtest>) cr.list();
            if (ltest.size() > 0) {
                request.setAttribute("ltest", ltest);
            }
            tr.commit();
            RequestDispatcher rd = request.getRequestDispatcher("lab_mytest.jsp");
            rd.forward(request, response);

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

    }
}

From source file:cust_update.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from  w  w  w  .j  av  a2 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, FileUploadException {
    response.setContentType("text/html;charset=UTF-8");

    HttpSession hs = request.getSession();
    PrintWriter out = response.getWriter();
    try {

        if (hs.getAttribute("user") != null) {
            Login ln = (Login) hs.getAttribute("user");

            System.out.println(ln.getUId());
            String firstn = "";
            String lastn = "";
            String un = "";
            String state = "";
            String city = "";
            int id = 0;
            String e = "";

            String num = "";
            String p = "";
            String custphoto = "";
            String custname = "";
            String area = "";

            // creates FileItem instances which keep their content in a temporary file on disk
            FileItemFactory factory = new DiskFileItemFactory();
            // Create a new file upload handler
            ServletFileUpload upload = new ServletFileUpload(factory);

            //get the list of all fields from request
            List<FileItem> fields = upload.parseRequest(request);
            // iterates the object of list
            Iterator<FileItem> it = fields.iterator();
            //getting objects one by one
            while (it.hasNext()) {
                //assigning coming object if list to object of FileItem
                FileItem fileItem = it.next();
                //check whether field is form field or not
                boolean isFormField = fileItem.isFormField();

                if (isFormField) {
                    //get the filed name 
                    String fieldName = fileItem.getFieldName();

                    if (fieldName.equals("fname")) {
                        firstn = fileItem.getString();
                        System.out.println(firstn);
                    } else if (fieldName.equals("id")) {
                        id = Integer.parseInt(fileItem.getString());
                    } else if (fieldName.equals("lname")) {
                        lastn = fileItem.getString();
                        System.out.println(lastn);
                    } else if (fieldName.equals("uname")) {
                        un = fileItem.getString();
                        System.out.println(un);
                    } else if (fieldName.equals("state")) {
                        state = fileItem.getString();
                        System.out.println(state);
                    } else if (fieldName.equals("city")) {
                        city = fileItem.getString();
                        System.out.println(city);
                    } else if (fieldName.equals("area")) {
                        area = fileItem.getString();
                    } else if (fieldName.equals("email")) {
                        e = fileItem.getString();
                        System.out.println(e);
                    }

                    else if (fieldName.equals("number")) {
                        num = fileItem.getString();
                        System.out.println(num);

                    } else if (fieldName.equals("pwd")) {
                        p = fileItem.getString();
                        System.out.println(p);
                    }

                } else {

                    //getting name of file
                    custphoto = new File(fileItem.getName()).getName();
                    //get the extension of file by diving name into substring
                    //  String extension=custphoto.substring(custphoto.indexOf(".")+1,custphoto.length());;
                    //rename file...concate name and extension
                    // custphoto=ln.getUId()+"."+extension;

                    System.out.println(custphoto);
                    try {

                        // FOR UBUNTU add GETRESOURCE  and GETPATH

                        String fp = "/home/rushin/NetBeansProjects/The_Asset_Consultancy/web/images/profilepic/";
                        // String filePath=  this.getServletContext().getResource("/images/profilepic").getPath()+"\\";
                        System.out.println("====" + fp);
                        fileItem.write(new File(fp + custphoto));
                    } catch (Exception ex) {
                        out.println(ex.toString());
                    }

                }

            }

            SessionFactory sf = NewHibernateUtil.getSessionFactory();
            Session ss = sf.openSession();
            Transaction tr = ss.beginTransaction();
            //            
            //             String op="";
            //                cr.add(Restrictions.eq("sId", Integer.parseInt(state)));
            //            ArrayList<StateMaster> ar = (ArrayList<StateMaster>)cr.list();
            //            if(ar.isEmpty()){
            //                
            //            }else{
            //                StateMaster sm = ar.get(0);
            //                op=sm.getSName();
            //                
            //            }

            CustomerDetail cd1 = (CustomerDetail) ss.get(CustomerDetail.class, id);
            System.out.println("cid is " + cd1.getCId());
            CustomerDetail cd = new CustomerDetail();

            cd.setUId(cd1.getUId());
            cd.setCId(cd1.getCId());
            cd.setCFname(firstn);
            cd.setCLname(lastn);
            cd.setCNum(num);
            cd.setCEmail(e);
            cd.setCState(state);
            cd.setCCity(city);
            cd.setCArea(area);
            cd.setCImg(custphoto);

            ss.evict(cd1);
            ss.update(cd);

            tr.commit();

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

        }

    }

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

}

From source file:SortedMapJUnitTest.java

@Test
public void createNewCar() {
    Session session = sessionFctry.openSession();
    Transaction tx = null;//from w ww . ja  v a 2 s. co m
    Integer returned_id = null;
    try {
        tx = session.beginTransaction();

        TreeMap carAdditions = new TreeMap();

        carAdditions.put("Skrzana kierownica", new CarAddition("MVC239Kierownica"));
        carAdditions.put("Skrzane siedzenia", new CarAddition("Cw3GDSSiedzenia"));
        carAdditions.put("Podgrzewane lusterka", new CarAddition("OPEL23432 lustra"));
        carAdditions.put("Chromowane felgi SkullCar 321", new CarAddition("SKULLCAR321"));

        Car newCar = new Car("Opel", "Corsa Mk2", 1998, 3700, "Diesel 2.0", carAdditions);

        returned_id = (Integer) session.save(newCar);
        tx.commit();
    } catch (Exception e) {
        e.printStackTrace();
    }
    session.close();

    //Sprawdz czy istnieje w bazie
    session = sessionFctry.openSession();
    tx = session.beginTransaction();

    Car getCar = (Car) session.get(Car.class, returned_id);
    tx.commit();

    assertNotNull(getCar); //gdy nie pusty to w bazie istnieje pojazd o tym id czyli ok
    session.close();

}

From source file:SortedMapJUnitTest.java

@Test(expected = PropertyAccessException.class)
public void TestCreateNewCarException01() {
    Session session = sessionFctry.openSession();
    Transaction tx = null;//from  www  . j a v  a  2s .  co m
    Integer returned_id = null;
    tx = session.beginTransaction();

    TreeMap carAdditions = new TreeMap();

    carAdditions.put("Skrzana kierownica", new String("MVC239Kierownica"));
    carAdditions.put("Skrzane siedzenia", new CarAddition("Cw3GDSSiedzenia"));
    carAdditions.put("Podgrzewane lusterka", new CarAddition("OPEL23432 lustra"));
    carAdditions.put("Chromowane felgi SkullCar 321", new CarAddition("SKULLCAR321"));

    Car newCar = new Car("Opel", "Corsa Mk2", 1998, 3700, "Diesel 2.0", carAdditions);

    returned_id = (Integer) session.save(newCar);
    tx.commit();
    session.close();

    //Sprawdz czy istnieje w bazie
    session = sessionFctry.openSession();
    tx = session.beginTransaction();

    Car getCar = (Car) session.get(Car.class, returned_id);
    tx.commit();

    assertNotNull(getCar); //gdy nie pusty to w bazie istnieje pojazd o tym id czyli ok
    session.close();

}

From source file:SortedMapJUnitTest.java

@Test
public void readCar() {
    /*zakadamy e w bazie isntnieje samochd o id 1 */
    final Integer carIDToTest = 2;

    Session session = sessionFctry.openSession();
    Transaction tx = null;//from   ww  w . ja v  a 2s. c om
    try {
        tx = session.beginTransaction();
        Car car = (Car) session.get(Car.class, carIDToTest);

        assertNotNull(car);

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