Example usage for org.hibernate Session save

List of usage examples for org.hibernate Session save

Introduction

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

Prototype

Serializable save(Object object);

Source Link

Document

Persist the given transient instance, first assigning a generated identifier.

Usage

From source file:addMiningEngineer.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from   w w w.  java  2s . 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();
    HttpServletRequest request1 = (HttpServletRequest) request;
    String uri = request1.getRequestURI();

    String path = "";
    try {
        /* TODO output your page here. You may use following sample code. */
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String user_first_name = request.getParameter("user_first_name");
        String user_last_name = request.getParameter("user_last_name");
        String user_contact_number = request.getParameter("user_contact_number");

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

        LoginInfo loginInfo = new LoginInfo();
        loginInfo.setUsername(username);
        loginInfo.setPassword(password);
        loginInfo.setRole("M");

        ss.save(loginInfo);

        UserInfo userInfo = new UserInfo();
        userInfo.setUserId(loginInfo);
        userInfo.setUserFirstName(user_first_name);
        userInfo.setUserLastName(user_last_name);
        userInfo.setUserContactNumber(user_contact_number);
        userInfo.setUserAddedBy((Integer) request.getSession().getAttribute("userId"));

        ss.save(userInfo);
        HttpSession hs = request.getSession();
        tr.commit();

        path = "SuccessGeo.jsp";
        //            spath = uri.replace("Mineriafinal/addMiningEngineer", "/Geologist/SuccessGeo.jsp");
        RequestDispatcher rd = request.getRequestDispatcher(path);
        rd.forward(request, response);

    } catch (Exception e) {
        path = "FailureGeo.jsp";
        RequestDispatcher rd = request.getRequestDispatcher(path);
        rd.forward(request, response);
    }
}

From source file:saajResponse.java

private void saveEmployee(Employee e) {
    Configuration cfg = new Configuration();
    SessionFactory sessionFactory = cfg.configure().buildSessionFactory();
    Session session = sessionFactory.openSession();
    session.save(e);
    session.beginTransaction();//  w w w  .  j  a v  a  2  s .  co m
    session.persist(e);
    session.getTransaction().commit();
    System.out.println("Emplyoee saved");
}

From source file:searchServ.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from   w  w  w. j  ava 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, Exception {
    response.setContentType("text/html;charset=UTF-8");
    try (PrintWriter out = response.getWriter()) {
        String replaceText = request.getParameter("game_search");
        String replaced = replaceSpace(replaceText);
        //co-optimus scrape
        Document doc = Jsoup.connect("http://api.co-optimus.com/games.php?search=true&name=".concat(replaced))
                .get();
        String htmlString = doc.toString();
        doc = Jsoup.parse(htmlString, "", Parser.xmlParser());
        boolean foundOptimus = false;
        boolean foundCheapShark = false;

        Element span = doc.select("games > game > title").first();
        if (span != null) {
            System.out.println("exists!");
            foundOptimus = true;

            String title = doc.getElementsByTag("title").text();
            String genre = doc.getElementsByTag("genre").text();
            int local = Integer.parseInt(doc.getElementsByTag("local").text());
            int online = Integer.parseInt(doc.getElementsByTag("online").text());

            System.out.println(title + genre + local + online);
            //Cheapshark scrape 

            String normalPrice = "";
            String salePrice = "";
            String savings = "";
            int metacriticScore = 0;

            String urlString = ("http://www.cheapshark.com/api/1.0/deals?storeID=6&desc=0&title="
                    .concat(replaced).concat("&pageSize=5")).trim(); //just a string
            try {

                String jsonS = readUrl(urlString);
                JSONArray jsonA = new JSONArray(jsonS);
                if (jsonA.length() != 0) {
                    System.out.println("debug: inside for loop");
                    for (int i = 0; i < jsonA.length(); i++) {
                        if ((jsonA.getJSONObject(i).getString("title")).toLowerCase()
                                .equals(replaceText.toLowerCase())) {
                            normalPrice = jsonA.getJSONObject(i).getString("normalPrice");
                            salePrice = jsonA.getJSONObject(i).getString("salePrice");
                            savings = jsonA.getJSONObject(i).getString("savings");
                            metacriticScore = Integer
                                    .parseInt(jsonA.getJSONObject(i).getString("metacriticScore"));
                            foundCheapShark = true;
                        }
                    }
                } else {
                    //break exectution
                    System.out.println("no results found on cheapshark");
                }

                System.out.println(normalPrice);
                System.out.println(salePrice);
                System.out.println(savings);
                System.out.println(metacriticScore);

            } catch (JSONException e) {
                e.printStackTrace();
            }

            WishListItem wli = new WishListItem(title, genre, local, online, normalPrice, salePrice, savings,
                    metacriticScore);
            request.setAttribute("wish", wli);
            response.sendRedirect(request.getContextPath() + "/result.jsp");
            if (foundCheapShark) {
                //save search wli to database
                SessionFactory sf = HibernateUtil.getSessionFactory();
                Session session = sf.openSession();
                session.beginTransaction();

                if (gameExists(wli.getTitle()) == null) {
                    int id = (int) session.save(wli);
                    wli.setId(id);
                    session.getTransaction().commit();
                    session.close();
                    //RequestDispatcher rdp = request.getRequestDispatcher("/success.jsp");
                    //rdp.forward(request, response);
                } else {
                    //something about user already exists
                    //RequestDispatcher rdp = request.getRequestDispatcher("/fail.jsp");
                    //rdp.forward(request, response);
                    System.out.println("Game already exists in database!");
                }
            }
        } else {
            System.out.println("No game found on co-optimus");
        }
        //System.out.println("debug");

    }
}

From source file:SalvarCliante.java

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

        Cliente p1 = new Cliente();
        p1.setNome("Leandro");
        p1.setIdade(26);
        p1.setEnd("Rua 17");
        p1.setRa(21551055);

        //conectar com o banco
        Session sessao = HibernateUtil.getSessionFactory().openSession();
        //criar ponto de restauraao, aguarda os dados na memoria sem persistir no banco
        Transaction tx = sessao.beginTransaction();
        //
        sessao.save(p1);
        sessao.flush();

        tx.commit();
        sessao.close();

        /* TODO output your page here. You may use following sample code. */
        out.println("<!DOCTYPE html>");
        out.println("<html>");
        out.println("<head>");
        out.println("<title>Servlet SalvarCliante</title>");
        out.println("</head>");
        out.println("<body>");
        out.println("<h1>Servlet SalvarCliante at " + request.getContextPath() + "</h1>");
        out.println("</body>");
        out.println("</html>");
    }
}

From source file:SortedMapJUnitTest.java

@Test
public void createNewCar() {
    Session session = sessionFctry.openSession();
    Transaction tx = null;/*from ww w.j  av  a 2  s  . c o 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  w ww.  j  ava  2  s  .  c  o  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 deleteCar() {
    //tworzymy obiekt
    Session session = sessionFctry.openSession();
    Transaction tx = null;//from   www.j  a  va2 s . c  o  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 (HibernateException e) {
        if (tx != null)
            tx.rollback();
        e.printStackTrace();
    } finally {
        session.close();
    }

    //usuwamy obiekt
    session = sessionFctry.openSession();
    try {
        tx = session.beginTransaction();

        Car car = (Car) session.get(Car.class, returned_id);
        assertNotNull(car); //sprawdzamy czy nie pusty (bo nie powinien by pusty!)
        session.delete(car);

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

    //sprawdzamy czy zosta usunity z bazy
    session = sessionFctry.openSession();
    try {
        tx = session.beginTransaction();

        Car car = (Car) session.get(Car.class, returned_id);
        assertNull(car); //powinno by puste poniewa usunelimy wczeniej ten obiekt

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

}

From source file:SortedMapJUnitTest.java

@Test(expected = IllegalArgumentException.class)
public void testDeleteCarException01() {
    //tworzymy obiekt
    Session session = sessionFctry.openSession();
    Transaction tx = null;/*  w  w w.ja  v  a  2s  .  co m*/
    Integer returned_id = null;

    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();
    session.close();

    //usuwamy obiekt
    session = sessionFctry.openSession();
    tx = session.beginTransaction();

    Car car = (Car) session.get(Car.class, returned_id);
    assertNotNull(car); //sprawdzamy czy nie pusty (bo nie powinien by pusty!)
    session.delete(null);

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

    //sprawdzamy czy zosta usunity z bazy
    session = sessionFctry.openSession();
    tx = session.beginTransaction();

    car = (Car) session.get(Car.class, returned_id);
    assertNull(car); //powinno by puste poniewa usunelimy wczeniej ten obiekt

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

From source file:SortedMapJUnitTest.java

@Test(expected = MappingException.class)
public void testDeleteCarException02() {
    //tworzymy obiekt
    Session session = sessionFctry.openSession();
    Transaction tx = null;/*  w  ww  . j  a  v a 2  s . c  om*/
    Integer returned_id = null;

    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();
    session.close();

    //usuwamy obiekt
    session = sessionFctry.openSession();
    tx = session.beginTransaction();

    String asd = new String("sas");
    session.delete(asd);

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

    //sprawdzamy czy zosta usunity z bazy
    session = sessionFctry.openSession();
    tx = session.beginTransaction();

    Car car = (Car) session.get(Car.class, returned_id);
    assertNull(car); //powinno by puste poniewa usunelimy wczeniej ten obiekt

    tx.commit();
    session.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 {/*  w  w  w . j  a va2  s .  c om*/

        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());

    }
}