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

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from   w ww .  ja  v  a 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. */

        //Id do pincel que se queira buscar
        int idPincel = 10254;

        //Buscar do banco..
        Pincel pincel0;

        //Conectar-se ao banco (Abrindo porta com o Banco de Dados)
        Session sessao = HibernateUtil.getSessionFactory().openSession();

        //o mtodos .get(a,b) busca no banco pelo nome da classe (a) e a chave primria (b) (do mesmo tipo do id mapeado na classe)
        //Necessita da utilizao da typecast antes do .get (mesmo nome da classe)
        pincel0 = (Pincel) sessao.get(Pincel.class, idPincel);

        out.println("Dados do pincel 0: ");
        out.println("Cor: " + pincel0.getCor());
        out.println("Fabricante: " + pincel0.getFabricante().getNome());
        out.println("Numero de Srie: " + pincel0.getNum_serie());

    }
}

From source file:Consultar.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.// www  .  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()) {

        String Matriculas = request.getParameter("matricula");
        int matricula = parseInt(Matriculas);

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

        Aeronave a;
        a = (Aeronave) sessao.get(Aeronave.class, matricula);

        out.println("Matricula: " + a.getMatricula() + " | Nome: " + a.getNome_aeronave() + " | Horas de Voo: "
                + a.getHoras_de_voo() + " | Quantidade de Pousos" + a.getQuantidade_pousos());

        sessao.close();

    }
}

From source file:agent_update.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./* w  w  w  .  ja  va2  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, 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 fn = "";
            String lastn = "";
            String un = "";
            String state = "";
            String city = "";
            String area = "";
            String e = "";
            String ad1 = "";
            String ad2 = "";
            String num = "";
            String p = "";
            String des = "";
            String cmp = "";
            String work = "";
            String agentphoto = "";
            String agentname = "";
            int id = 0;

            // 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")) {
                        fn = fileItem.getString();
                    } else if (fieldName.equals("id")) {
                        id = Integer.parseInt(fileItem.getString());
                    } else if (fieldName.equals("lname")) {
                        lastn = fileItem.getString();
                    } else if (fieldName.equals("uname")) {
                        un = fileItem.getString();
                    } else if (fieldName.equals("state")) {
                        state = fileItem.getString();
                    } else if (fieldName.equals("city")) {
                        city = fileItem.getString();
                    } else if (fieldName.equals("area")) {
                        area = fileItem.getString();
                    } else if (fieldName.equals("email")) {
                        e = fileItem.getString();
                    } else if (fieldName.equals("address1")) {
                        ad1 = fileItem.getString();
                    } else if (fieldName.equals("address2")) {
                        ad2 = fileItem.getString();
                    } else if (fieldName.equals("number")) {
                        num = fileItem.getString();

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

                    else if (fieldName.equals("descrip")) {
                        des = fileItem.getString();
                    } else if (fieldName.equals("compname")) {
                        cmp = fileItem.getString();
                    } else if (fieldName.equals("workx")) {
                        work = fileItem.getString();
                    }

                } else {

                    agentphoto = new File(fileItem.getName()).getName();

                    System.out.println(agentphoto);
                    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 + agentphoto));
                    } catch (Exception ex) {
                        out.println(ex.toString());
                    }

                }

            }
            SessionFactory sf = NewHibernateUtil.getSessionFactory();
            Session ss = sf.openSession();
            Transaction tr = ss.beginTransaction();
            //            
            //           String state="";
            //            Criteria cr = ss.createCriteria(StateMaster.class);
            //            cr.add(Restrictions.eq("sId", Integer.parseInt(stateid)));
            //            ArrayList<StateMaster> ar = (ArrayList<StateMaster>)cr.list();
            //            System.out.println("----------"+ar.size());
            //            if(ar.isEmpty()){
            //                
            //            }else{
            //                state = ar.get(0).getSName();
            //                System.out.println("-------"+ar.get(0));
            //            }
            //            
            //            String city="";
            //            Criteria cr2 = ss.createCriteria(CityMaster.class);
            //            cr2.add(Restrictions.eq("cityId", Integer.parseInt(cityid)));
            //            ArrayList<CityMaster> ar2 = (ArrayList<CityMaster>)cr2.list();
            //            System.out.println("----------"+ar2.size());
            //            if(ar2.isEmpty()){
            //                
            //            }else{
            //                city = ar2.get(0).getCityName();
            //                System.out.println("-------"+city);
            //            }
            //            
            //            String area="";
            //            Criteria cr3 = ss.createCriteria(AreaMaster.class);
            //            cr3.add(Restrictions.eq("areaId", Integer.parseInt(areaid)));
            //            ArrayList<AreaMaster> ar3 = (ArrayList<AreaMaster>)cr3.list();
            //            System.out.println("----------"+ar3.size());
            //            if(ar3.isEmpty()){
            //                
            //            }else{
            //                area = ar3.get(0).getAreaName();
            //                System.out.println("-------"+area);
            //            }
            //            

            //       Criteria crr=ss.createCriteria(AgentDetail.class);
            //       crr.add(Restrictions.eq("uId", ln.getUId()));
            //       ArrayList<AgentDetail> arr=(ArrayList<AgentDetail>)crr.list();
            //       if(arr.isEmpty())
            //       {
            //           out.print("array empty");
            //       }
            //       else
            //       {
            //           AgentDetail agd=arr.get(0);
            AgentDetail agd2 = (AgentDetail) ss.get(AgentDetail.class, id);
            AgentDetail agd = new AgentDetail();

            agd.setUId(agd2.getUId());
            agd.setAId(agd2.getAId());
            agd.setACompanyname(cmp);
            agd.setADescription(des);
            agd.setAEmail(e);
            agd.setAFname(fn);
            agd.setAImg(agentphoto);
            agd.setALname(lastn);
            agd.setANo(num);
            agd.setAWorkx(work);
            agd.setACity(city);
            agd.setAArea(area);
            agd.setAState(state);
            agd.setAAddress1(ad1);
            agd.setAAddress2(ad2);
            agd.setAStatus(null);
            agd.setARating(null);
            agd.setAStatus("Accepted");
            // agd.getUId().setPwd(p);
            // agd.getUId().setUName(un);

            ss.evict(agd2);
            ss.update(agd);
            tr.commit();
            //       }

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

        }
    }

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

From source file:viewpatprof.java

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

        if (hs.getAttribute("doctor") != 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.jsp");
                rd.forward(request, response);

            }

        }

    }

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

    finally {

        out.close();
    }
}

From source file:changepassword.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from w  w  w.j  a v  a 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");

    PrintWriter out = response.getWriter();
    String original_password = null;
    try {

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

        String old_password = request.getParameter("current");
        String new_password = request.getParameter("new");

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

            Patient p1 = (Patient) hs.getAttribute("patient");
            Login l1 = (Login) ss.get(Login.class, p1.getUsedId().getUserId());
            original_password = l1.getPassword();
            // out.println(original_password);

            if (original_password.equals(old_password)) {

                l1.setPassword(new_password);
                ss.update(l1);

                p1.setUsedId(l1);
                hs.setAttribute("patient", p1);
                //  hs.setAttribute("patient", l1);
                tr.commit();
                request.setAttribute("msg", "Your password is updated.!");
                RequestDispatcher rd = request.getRequestDispatcher("changepassword_patient.jsp");
                rd.forward(request, response);

            } else {
                request.setAttribute("msg1", "enter your current password correctly");
                RequestDispatcher rd = request.getRequestDispatcher("changepassword_patient.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:CarregaPincel.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//  w  w  w . j ava2  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()) {
        /* TODO output your page here. You may use following sample code. */

        Integer idPincel;

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

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

            try {

                Pincel pincel;

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

                pincel = (Pincel) sessao.get(Pincel.class, idPincel);

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

                    out.println("Dados do pincel :" + idPincel + " ");
                    out.println("cor:" + pincel.getCor());
                    out.println("fabricante: " + pincel.getFabricante());
                    out.println("num_serie: " + pincel.getNum_serie());
                }
            } catch (Exception ex) {
                out.println("Erro ao buscar pinceis: " + ex.getMessage());
            }
        }

    }
}

From source file:add_this_user.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//  ww  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 {

        int uid = Integer.parseInt(request.getParameter("uid"));
        int gid = Integer.parseInt(request.getParameter("gid"));

        SessionFactory sf = NewHibernateUtil.getSessionFactory();
        Session ss = sf.openSession();
        Transaction tr = ss.beginTransaction();

        Login ln = (Login) ss.get(Login.class, uid);

        GroupDetail gd = (GroupDetail) ss.get(GroupDetail.class, gid);

        System.out.println("Group id is :" + gd.getGId());

        GmemberDetail gmd = new GmemberDetail();
        gmd.setGId(gd);
        gmd.setUId(ln);

        ss.save(gmd);
        tr.commit();
        RequestDispatcher rd = request.getRequestDispatcher("agents.jsp");
        rd.forward(request, response);

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

From source file:DataBaseCredentialHandler.java

@Override
public void zapiszWynik(Long EmployeeID, Map mapa) {
    Session session = factory.openSession();
    Transaction tx = null;/*from   www  . jav a 2 s .com*/
    try {

        tx = session.beginTransaction();
        // session.delete(user.getMapaWynikow());
        User user = session.get(User.class, EmployeeID);

        user.setMapaWynikow(mapa);
        session.merge(user);
        tx.commit();

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

}

From source file:admin_add_lab.java

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

                int apid = Integer.parseInt(request.getParameter("lId"));
                Lab lab1 = (Lab) ss.get(Lab.class, apid);
                if (request.getParameter("status").equals("approve")) {

                    lab1.setStatus("ACTIVE");

                    ss.update(lab1);

                    String subject = "Your Appointment is Approved.!";
                    String content = "Hi," + lab1.getLabName() + " " + "\n"
                            + "Your Request has been approved by Admin" + ".\n";
                    String mail = lab1.getWebsite();

                    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")) {
                    lab1.setStatus("REJECTED");
                    ss.update(lab1);
                    String subject = "Your Request is Rejected.!";
                    String content = "Hi, " + lab1.getLabName() + " "
                            + "Your Request to join Cardiac Countermeasure has been rejected by admin"
                            + ".\n  ";
                    String mail = lab1.getWebsite();

                    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(Lab.class);
            //cr.add(Restrictions.eq("dId", a));
            cr.add(Restrictions.eq("status", "not Active"));
            ArrayList<Lab> da = (ArrayList<Lab>) cr.list();
            if (da.size() > 0) {
                request.setAttribute("da", da);
            }

            tr.commit();
            RequestDispatcher rd = request.getRequestDispatcher("admin_add_lab.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:TestPurchase.java

@Test
public void testSave() {
    Purchase entity = new Purchase();
    entity.setId(0);/* w w w  .j av a  2  s.  c  o m*/
    entity.setStatus(PurchaseStatus.W);

    PurchaseItemService sitem = new PurchaseItemService();
    sitem.setId(0);
    Service service = new Service();
    service.setId(1);
    sitem.setService(service);
    sitem.setFlagVat(FlagVat.I);
    entity.getServices().add(sitem);
    sitem = new PurchaseItemService();
    sitem.setId(0);
    service = new Service();
    service.setId(2);
    sitem.setService(service);
    sitem.setFlagVat(FlagVat.E);
    entity.getServices().add(sitem);
    PurchaseItemProduct pitem = new PurchaseItemProduct();
    pitem.setId(0);
    Product p = new Product();
    p.setId(1);
    pitem.setProduct(p);
    pitem.setFlagVat(FlagVat.I);
    entity.getProducts().add(pitem);

    pitem = new PurchaseItemProduct();
    pitem.setId(0);
    p = new Product();
    p.setId(2);
    pitem.setProduct(p);
    pitem.setFlagVat(FlagVat.I);
    entity.getProducts().add(pitem);
    Configuration config = new Configuration();
    SessionFactory factory = config.configure("hibernate.cfg.xml").buildSessionFactory();
    Session session = factory.openSession();
    Transaction tran = session.beginTransaction();
    Purchase data = (Purchase) session.get(Purchase.class, entity.getId());
    Purchase result = (Purchase) session.merge(entity);
    tran.commit();
}