Example usage for org.hibernate Session saveOrUpdate

List of usage examples for org.hibernate Session saveOrUpdate

Introduction

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

Prototype

void saveOrUpdate(Object object);

Source Link

Document

Either #save(Object) or #update(Object) the given instance, depending upon resolution of the unsaved-value checks (see the manual for discussion of unsaved-value checking).

Usage

From source file:testUTF.java

public static void main(String[] args) {
    Supplier sup = new Supplier();
    sup.setName("?i l ht b Ch? Mt T");
    sup.setId(6);/*from   w ww . ja va2 s .  com*/
    Session ses = utils.HibernateUtils.getSessionFactory().getCurrentSession();
    ses.beginTransaction();
    ses.saveOrUpdate(sup);
    ses.getTransaction().commit();
    System.exit(0);
}

From source file:StartupListener.java

@Override
public void contextInitialized(ServletContextEvent sce) {
    Person p = new Person();
    p.setName("Pekka");
    Person p1 = new Person();
    p1.setName("Ilpo");
    Car hyundai = new Car();
    hyundai.setOwner(p);//from   w w  w  . j a v  a2 s  .  co  m
    hyundai.setPrice(2000.6);
    Car kia = new Car();
    kia.setOwner(p);
    kia.setPrice(1800.3);
    Car peugeot = new Car();
    peugeot.setOwner(p1);
    peugeot.setPrice(1250.1);

    p.getCars().add(hyundai);
    p.getCars().add(kia);
    p1.getCars().add(peugeot);
    Session session = HibernateUtil.getSessionFactory().openSession();
    session.beginTransaction();
    session.saveOrUpdate(p);
    session.saveOrUpdate(p1);
    session.saveOrUpdate(peugeot);
    session.saveOrUpdate(kia);
    session.saveOrUpdate(hyundai); // save changes in object graph starting at t
    // save changes in object graph starting at u
    session.getTransaction().commit();
    session.close();
}

From source file:writeblog.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from  w ww  .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 ss1 = sf.getCurrentSession();
        Transaction tr1 = ss1.getTransaction();
        tr1.begin();
        HttpSession hs = request.getSession();
        if (hs.getAttribute("doctor") != null) {

            Doctor pi = (Doctor) hs.getAttribute("doctor");

            if (request.getParameter("subject") != null && request.getParameter("content") != null) {

                String sub = request.getParameter("subject");
                String con = request.getParameter("content");
                request.setAttribute("msg", "Blog Created..!");
                Blog b = new Blog();
                if (request.getParameter("updateblogid") != null) {
                    b.setBlogId(Integer.parseInt(request.getParameter("updateblogid")));
                    request.setAttribute("msg", "Blog Updated..!");
                }
                b.setBlogname(sub);
                b.setBlogdescription(con);
                b.setDId(pi);
                b.setBlogView(20);
                b.setImageUrl("abc.jpg");
                b.setBlogDate(new Date().toString());
                ss1.saveOrUpdate(b);
            }

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

                Blog b = (Blog) ss1.get(Blog.class, Integer.parseInt(request.getParameter("blogid")));
                request.setAttribute("editblog", b);
            }

            Criteria cr1 = ss1.createCriteria(Blog.class);
            cr1.add(Restrictions.eq("dId", pi));
            ArrayList<Blog> dblog = (ArrayList<Blog>) cr1.list();
            if (dblog.size() > 0) {
                request.setAttribute("dblog", dblog);
            }

            tr1.commit();
            RequestDispatcher rd = request.getRequestDispatcher("doctor_write_blog1.jsp");
            rd.forward(request, response);

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

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

From source file:SaveTransactionServ.java

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    try {//www.  j  a v  a 2s .  c  o m

        String TransactionId = request.getParameter("txn_id");
        String grossAmount = request.getParameter("payment_gross");
        String paymentStatus = request.getParameter("payment_status");
        String orderId = request.getParameter("custom");

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

        HttpSession hs = request.getSession();
        OrderDetails od = (OrderDetails) hs.getAttribute("OrderDetails");
        String path = "";
        if (paymentStatus.equals("Completed")) {
            System.out.println("Inside Iff Block");
            OrderDetails od2 = new OrderDetails();
            od2.setOrderId(od.getOrderId());
            od2.setAmount(od.getAmount());
            od2.setPid(od.getPid());
            od2.setQty(od.getQty());
            od2.setUserid(od.getUserid());
            od2.setTstatus("Success");

            ss.saveOrUpdate(od2);

            TransactionDetails td = new TransactionDetails();
            td.setTransactionID(request.getParameter("txn_id"));
            td.setStatus(paymentStatus);
            td.setOrderID(od2);
            ss.save(td);

            tr.commit();
            path = "PayPalResponse.jsp";
        } else {
            TransactionDetails td = new TransactionDetails();
            td.setTransactionID(request.getParameter("txn_id"));
            td.setTransactionID(paymentStatus);
            td.setOrderID(od);
            ss.save(td);

            tr.commit();
            path = "PaymentFailed.jsp";
        }

        RequestDispatcher rd = request.getRequestDispatcher(path);
        rd.forward(request, response);

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

    }
}

From source file:submitaction.java

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

    String username = (String) session.getAttribute("username");
    String dpimage = (String) session.getAttribute("dpimage");

    if (username == null)
        response.sendRedirect("login.jsp");
    else {

        String problemcode = (String) request.getParameter("q");
        String contestcode = (String) request.getParameter("c");
        String contestpath = Path.getArgPath("contests", contestcode);
        String userpath = Path.getArgPath("users", username);

        /* =========================== user not registered : redirect to index page ====================*/
        Connection con = null;
        Config c = new Config();
        int check = 0;
        Timestamp sdate = null, edate = null, ts = null;
        try {

            con = c.getcon();
            Statement stmt7 = con.createStatement();
            Statement stmt8 = con.createStatement();

            String sq = "Select count(*) as col from " + contestcode + "ranking where userid='" + username
                    + "'";
            String sq2 = "Select * from ContestInfo where contestcode='" + contestcode + "'";
            ResultSet rs8 = stmt8.executeQuery(sq2);
            if (rs8.next()) {
                sdate = rs8.getTimestamp("starttime");
                edate = rs8.getTimestamp("endtime");
            }
            java.util.Date date = new java.util.Date();
            ts = new Timestamp(date.getTime());

            //out.println(sq);
            ResultSet rs7 = stmt7.executeQuery(sq);
            if (rs7.next())
                check = Integer.parseInt(rs7.getString("col"));

        } catch (Exception e) {
        }

        if (!(ts.compareTo(sdate) > 0 && ts.compareTo(edate) < 0))
            response.sendRedirect("contestshow.jsp?c=PRACTICE");
        else if (check == 0)
            response.sendRedirect("index.jsp?register=True");
        else {
            /* ========================== get browsefile or editorfile  ==================== */

            Part filePart = null;
            String browsefile = null, ext = null, editorfile = null, language = null;
            int l = 0;
            try {
                MultipartRequest m = new MultipartRequest(request, userpath);
                filePart = request.getPart("test2");
                browsefile = (String) m.getFilesystemName("test2");

                editorfile = (String) m.getParameter("test1");

                language = (String) m.getParameter("language");

                HashMap<String, String> map = new HashMap<String, String>();
                map.put("AWK", "awk");
                map.put("Bash", "sh");
                map.put("C++", "cpp");
                map.put("C", "c");
                map.put("C#", "cs");
                map.put("Java", "java");
                map.put("Haskell", "hs");
                map.put("Perl", "pl");
                map.put("Pike", "pike");
                map.put("Python2.7", "py");
                map.put("Python3", "py");
                map.put("PHP", "php");
                map.put("Pascal", "pas");
                map.put("Ruby", "rb");
                ext = (String) map.get(language);
                l = editorfile.length();
            } catch (Exception e) {
                out.print("hi");
                out.flush();
            }

            if (l == 0 && browsefile == null) {
                //no file selected 
                response.sendRedirect("submit.jsp?q=" + problemcode + "&c=" + contestcode);
            } else {

                BufferedReader br = null;
                BufferedWriter bout = null;

                SessionFactory factory = new ConnectionProvider().getSessionFactory();
                Session s = factory.openSession();
                String id = "", st = "";
                Query q = null;
                Object[] ob = null;
                Transaction t = null;
                /* ==================== unique name : get from id table ============= */

                try {

                    st = "FROM Id id";
                    q = s.createQuery(st);
                    List<Id> users = q.list();
                    ob = users.toArray();
                    int preid = ((Id) ob[0]).getId();
                    id = "" + (preid + 1);
                    t = s.beginTransaction();
                    s.delete((Id) ob[0]);
                    s.saveOrUpdate(new Id(preid + 1));
                    t.commit();
                } catch (Exception e) {
                }

                /* ================== rename filenames and create folder and copy files in env =========== */
                //out.print(browsefile);out.flush();
                String browsefilepath = userpath + browsefile;
                String problempath = Path.getArgPath("contests", contestcode, problemcode); // for stdin.txt

                String codefilename = "Main" + id;

                //       rename procedure
                File file = new File(browsefilepath);
                // File (or directory) with new name
                File file2 = new File(userpath + codefilename + "." + ext);
                // Rename file (or directory)
                boolean success = file.renameTo(file2);

                //creating new folder for each sumission in env dir.

                String envPath = Path.getArgPath("env", codefilename);
                File dir = new File(envPath);
                if (!dir.exists()) {
                    dir.mkdir();
                }

                // copy file to env folder inside mkdir folder
                String userfilepath = userpath + codefilename + "." + ext;
                envPath = envPath + ("Main" + id + "." + ext);

                try {

                    if (editorfile.length() != 0) {
                        //out.print("this running");
                        bout = new BufferedWriter(new FileWriter(userfilepath), 10000);
                        bout.write(editorfile);
                        bout.close();

                        bout = new BufferedWriter(new FileWriter(envPath), 10000);
                        bout.write(editorfile);
                        bout.close();

                    } else {
                        br = new BufferedReader(new FileReader(userfilepath));
                        bout = new BufferedWriter(new FileWriter(envPath), 10000);
                        String line = "";
                        while ((line = br.readLine()) != null) {
                            bout.write(line + "\n");
                            bout.flush();
                        }
                        bout.flush();
                        bout.close();
                        br.close();
                    }

                } catch (Exception e) {
                }

                /* ======================= Running judge now  | ranking update  | status update ============ */

                // out.print((String)m.getParameter("language"));out.flush();
                Problems now = null;
                Date d = null;
                try {
                    st = "FROM Problems S WHERE S.problemcode='" + (String) request.getParameter("q") + "'";
                    q = s.createQuery(st);
                    List<Problems> ques = q.list();
                    ob = ques.toArray();
                    now = (Problems) ob[0];
                    d = new Date();
                    //out.print(now.toString());out.flush();

                } catch (Exception e) {
                    out.print("msg1=" + e.getMessage());
                }

                try {
                    Timestamp tmp = new Timestamp(d.getTime());

                    //out.println(language);
                    Q queue = new Q(codefilename, username, language, ext, problempath, "unjudge",
                            Double.parseDouble(now.getTimelimit()), "null", tmp, 0, 0, contestcode, 0,
                            problemcode, now.getTestfiles());
                    //do the judge work ;
                    t = s.beginTransaction();
                    s.saveOrUpdate(queue);
                    t.commit();
                } catch (Exception ex) {
                    out.print("msg2=" + ex.getMessage());
                } finally {
                    s.close();
                    factory.close();
                }

                // Show exit code of process
                //         out.println("Procefdsfdsfdsss exited with code = ");
                try {

                    //judge the solution         
                    //out.print("judge process starts "); out.flush();
                    final String[] cmd = { "/bin/bash", "-c", "cd " + Path.getPath() + " ; python judge.py" };
                    Runtime.getRuntime().exec(cmd);
                    //p.waitFor();

                    // inner class to run process without wait  outside main thread
                    /*  new Thread(new Runnable() {
                           public void run() {
                             try
                             {
                                 Runtime.getRuntime().exec(cmd);
                                 //p.waitFor();
                             }catch(Exception e){}
                       }
                     }).start(); 
                            
                    */
                    String problemid = (String) request.getParameter("q");
                    response.sendRedirect(
                            "status.jsp?q=" + problemid + "&c=" + contestcode + "&code=" + codefilename);
                    /* int chk = 0;   
                     while(chk == 0)
                     {
                            Thread.sleep(1);   
                            String query="Select count(*) as ch , status from " + contestcode+"submissions where username='"+username + "' and codefilename='"+codefilename+"'";
                            //out.println(query);
                                   
                            String pid = ""+problemid.charAt(problemid.length()-1);
                            //out.println(query);
                            ResultSet rs = stmt.executeQuery(query);
                            if(rs.next()){
                                chk = Integer.parseInt(rs.getString("ch"));
                                if(chk == 0)
                                 continue;
                                        
                                out.print("<style>#loading{visibility: hidden;</style>");              
                                out.println(rs.getString("status"));
                                        
                                if(rs.getString("status").compareTo("Accepted")==0)
                                {
                                    String sq = "Select * from "+contestcode+"ranking where userid='"+username+"'";
                                    //out.println(sq);
                                    ResultSet rs6 = stmt6.executeQuery(sq);
                                    if(rs6.next())
                                    {
                                        //out.println("hhhdsffsdkbhn");
                                        if(rs6.getString(pid+"score").compareTo("0") == 0)
                                        {
                    query = "UPDATE "+contestcode+"ranking SET "+pid+"score=100.0, "+pid+"time="+tc+" where userid='"+username+"'"; 
                    //out.println(query);
                    stmt2.executeUpdate(query);
                                        }
                                    }
                                }
                                else{
                                    String sql = "Select * from "+contestcode+"ranking where userid='"+username+"'";
                                    //out.println(sql);
                                    ResultSet rs3 = stmt2.executeQuery(sql);
                                    if(rs3.next())
                                    {
                                        //out.println("hhhdsffsdkbhn");
                                        if(rs3.getString(pid+"score").compareTo("0") == 0)
                                        {
                    int penalty = Integer.parseInt(rs3.getString(pid+"penalty"));
                    penalty += 1;
                    query = "UPDATE "+contestcode+"ranking SET "+pid+"penalty="+penalty+" where userid='"+username+"'";
                     //out.println(query);
                    stmt3.executeUpdate(query);
                                        }
                                    }
                                                
                                }
                                        
                                String sql = "Select * from "+contestcode+"ranking where userid='"+username+"'";
                                ResultSet rs5 = stmt5.executeQuery(sql);
                                //out.println("hi"+nop);
                                int total_penalty = 0;
                                Double total_score=0.0;
                                long total_time = 0;
                                char ch='A';
                                if(rs5.next())
                                {
                                    //out.println(rs5.getString("Apenalty"));
                            
                                    for(int i=0;i<nop;i++,ch++)
                                    {
                                        //out.println(ch);
                                        total_penalty += Integer.parseInt(rs5.getString(ch+"penalty"));
                                        total_score += Double.parseDouble(rs5.getString(ch+"score"));
                                        total_time += Long.parseLong(rs5.getString(ch+"time"));
                                        //out.println(total_penalty+" "+total_score+" "+total_time);
                                    }
                                    //out.println("hello");
                                    total_time += total_penalty * 20000*60;
                                    //Timestamp nt = new Timestamp(total_time);
                                    query = "UPDATE "+contestcode+"ranking SET penalty="+total_penalty+", score="+total_score+", time="+total_time+" where userid='"+username+"'";
                                    //out.println(query);
                                    stmt4.executeUpdate(query);
                                    out.flush();
                                }
                            }
                     }//while
                    */
                    con.close();
                    //  response.sendRedirect("index.jsp");
                } catch (Exception e) {
                } finally {
                    out.close();
                }

                /*
                        
                    out.print("<style>#loading{visibility: hidden;</style>");
                }
                          
                */
            }
        } //inner else due to sendRedirect
    } //else due to sendRedirect
}

From source file:doc_profile.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from   www .ja 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 ss1 = sf.openSession();
        Transaction tr1 = ss1.beginTransaction();
        // tr1.begin();
        HttpSession hs = request.getSession(true);
        if (hs.getAttribute("doctor") != null) {

            Doctor pi = (Doctor) hs.getAttribute("doctor");
            if (request.getParameter("btn_update") != null) {

                Doctor dd = (Doctor) ss1.get(Doctor.class, pi.getDId());

                Addressdetails ad = dd.getAddressid();
                String line = request.getParameter("line1");
                ad.setLine1(line.trim());
                ad.setLine2(request.getParameter("line2").trim());
                ad.setPincode(request.getParameter("pincode").trim());
                ss1.saveOrUpdate(ad);

                dd.setDFirstname(request.getParameter("p_firstname").trim());
                dd.setDLastname(request.getParameter("p_lastname").trim());
                dd.setGender(request.getParameter("gender").trim());
                dd.setBirthDate(request.getParameter("birth_date").trim());
                dd.setContactnum(request.getParameter("contact_num").trim());
                dd.setEmailId(request.getParameter("email_id").trim());

                ss1.saveOrUpdate(dd);
                pi = dd;
            }
            tr1.commit();
            request.setAttribute("pdata", pi);
            RequestDispatcher rd = request.getRequestDispatcher("Doctor_myprofile.jsp");
            rd.forward(request, response);

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

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

        out.close();
    }
}

From source file:abd.p1.bd.UserDAO.java

public void saveOrUpdate(Usuario user) {
    Session s = sf.openSession();
    Transaction tr = s.beginTransaction();
    s.saveOrUpdate(user);
    tr.commit();//  w ww. ja v a  2s .c  o  m
    s.close();
}

From source file:abid.password.swing.dao.hibernate.AbstractHibernateDao.java

License:Apache License

public void saveOrUpdate(T entity) {
    Session session = sessionFactory.openSession();
    try {//  w  w  w. j  a va  2  s .  c  om
        Transaction transaction = session.beginTransaction();
        session.saveOrUpdate(entity);
        transaction.commit();
    } finally {
        session.close();
    }
}

From source file:Activity.activitySetter.java

public static void updateActivityById(Integer activityId, String activityName, Category category) {
    Session session = HibernateUtil.getSessionFactory().openSession();
    session.beginTransaction();//from   w  w w  .  j a  v  a2s.  c o m
    Activity updateAct = new Activity();
    updateAct = (Activity) session.get(Activity.class, activityId);
    Hibernate.initialize(updateAct);
    updateAct.setActivityName(activityName);
    updateAct.setCategory(category);
    session.merge(updateAct);
    session.saveOrUpdate(updateAct);
    session.getTransaction().commit();

}

From source file:Activity.activitySetter.java

public static void updateActivityReportById(Integer activityReportId, Activity activity,
        String activityDescription, Timestamp activityStartTime, Timestamp activityEndTime) {
    Session session = HibernateUtil.getSessionFactory().openSession();
    session.beginTransaction();/*from w  w  w . j  a  v  a  2 s. c  om*/
    ActivityReport updateActRep = new ActivityReport();
    updateActRep = (ActivityReport) session.get(ActivityReport.class, activityReportId);
    Hibernate.initialize(updateActRep);
    updateActRep.setActivity(activity);
    updateActRep.setActivityDescription(activityDescription);
    updateActRep.setActivityStartTime(activityStartTime);
    updateActRep.setActivityEndTime(activityEndTime);
    session.merge(updateActRep);
    session.saveOrUpdate(updateActRep);
    session.getTransaction().commit();

}