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

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.// ww  w.  j  av  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 {
        String path = "refresh_page.jsp";
        SessionFactory sf = HibernateUtil.getSessionFactory();
        Session ss = sf.openSession();
        Transaction tr = ss.beginTransaction();

        Addressdetails ad = new Addressdetails();
        ad.setLine1(request.getParameter("line1"));
        ad.setLine2(request.getParameter("line2"));
        ad.setCity(request.getParameter("city"));
        ad.setState(request.getParameter("state"));
        ad.setPincode(request.getParameter("pincode"));
        ss.save(ad);

        Login lo = new Login();
        lo.setUsername(request.getParameter("user_id"));
        lo.setPassword(request.getParameter("password"));
        lo.setRole("Laboratory");
        ss.save(lo);

        Lab la = new Lab();
        la.setLabName(request.getParameter("lab_name"));
        la.setWebsite(request.getParameter("website"));
        la.setContactNum(request.getParameter("cont_num"));
        la.setAddressid(ad);
        la.setStatus("not Active");
        la.setUserId(lo);
        ss.save(la);

        tr.commit();

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

        out.println("success");

    }

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

}

From source file:MainVehicle.java

public static void main(String h[]) {
    Vehicle v1 = new Vehicle();
    v1.setVid(1);//from www  .j a  va  2s.  c  o m
    v1.setVname("some vehicle");

    TwoWheeler tw = new TwoWheeler();
    tw.setVid(12);
    tw.setVname("bike");
    tw.setHandleBar("bike handle bar");

    FourWheeler fw = new FourWheeler();
    fw.setVid(13);
    fw.setVname("car");
    fw.setSteeringWheel("car's streeing wheel");

    Configuration conf = new Configuration();
    conf.configure("hibernate.cfg.xml");
    SessionFactory factory = conf.buildSessionFactory();
    Session sess = factory.openSession();
    Transaction trx = sess.beginTransaction();
    sess.save(v1);
    sess.save(tw);
    sess.save(fw);

    trx.commit();
    sess.close();

}

From source file:add_this_user.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from   w w w.j  a  v a2s. 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:prop_fb_serv.java

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

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

        if (hs.getAttribute("user") != null) {
            PropDetail pd = (PropDetail) hs.getAttribute("propobj");
            Login ln = (Login) hs.getAttribute("user");
            String content = request.getParameter("content");

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

            PropFeedback pf = new PropFeedback();

            pf.setPId(pd);
            pf.setUId(ln);
            pf.setComment(content);

            pf.setTime(new Date(System.currentTimeMillis()));

            ss.save(pf);
            tr.commit();

            RequestDispatcher rd = request.getRequestDispatcher("getstate?id=9");
            rd.forward(request, response);

        }
    }

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

From source file:DataBaseCredentialHandler.java

@Override
public Long zapisNowegoUzytkownika(Credentials Cr1) throws IOException {
    Session session = factory.openSession();
    Transaction tx = null;/*from  www.j  ava 2  s .  co m*/
    Long employeeID = null;

    try {
        tx = session.beginTransaction();

        User user = new User(Cr1);
        employeeID = (Long) session.save(user);
        tx.commit();
    } catch (HibernateException e) {
        if (tx != null)
            tx.rollback();
        e.printStackTrace();
    } finally {
        session.close();
    }
    return employeeID;
}

From source file:UserManagerTest.java

@Test
public void defaultData() {

    try {//  w  w w  .ja v a  2s .c  o m
        Role role1 = new Role();
        role1.setName("ADMIN");
        role1.setDescription("Admin");

        Role role2 = new Role();
        role2.setName("LANDLORD");
        role2.setDescription("Landlord");

        Role role3 = new Role();
        role3.setName("TANENT");
        role3.setDescription("Tanent");

        Session session = HibernateUtil.getSession();
        session.beginTransaction();
        session.save(role1);
        session.save(role2);
        session.save(role3);
        session.getTransaction().commit();

        AccountStatus activeStatus = new AccountStatus();
        activeStatus.setDescription("Active");
        AccountStatus inActiveStatus = new AccountStatus();
        inActiveStatus.setDescription("Inactive");
        session = HibernateUtil.getSession();
        session.beginTransaction();
        session.save(activeStatus);
        session.save(inActiveStatus);
        session.getTransaction().commit();

        Session session2 = HibernateUtil.getSession();
        session2.beginTransaction();
        User user1 = new User();
        user1.setFirstName("Nazmul");
        user1.setLastName("Hasan");
        user1.setUserName("nazmul");
        user1.setPassword("pass");
        user1.setEmail("nazmul@gmail.com");
        user1.setCellNo("01711123456");
        user1.setImg("user.jpg");
        user1.setIsVerified(false);
        user1.setAccountStatus(activeStatus);

        User user2 = new User();
        user2.setFirstName("Alamgir");
        user2.setLastName("Kabir");
        user2.setUserName("alamgir");
        user2.setPassword("pass");
        user2.setEmail("alamgir@gmail.com");
        user2.setCellNo("01722123456");
        user2.setImg("user.jpg");
        user2.setIsVerified(false);
        user2.setAccountStatus(activeStatus);

        session2.save(user1);
        session2.save(user2);
        session2.getTransaction().commit();

        Session session3 = HibernateUtil.getSession();
        session3.beginTransaction();

        UserRoles userRoles1 = new UserRoles();
        userRoles1.setRole(role1);
        userRoles1.setUser(user1);

        UserRoles userRoles2 = new UserRoles();
        userRoles2.setRole(role2);
        userRoles2.setUser(user1);

        UserRoles userRoles3 = new UserRoles();
        userRoles3.setRole(role3);
        userRoles3.setUser(user1);

        UserRoles userRoles4 = new UserRoles();
        userRoles4.setRole(role3);
        userRoles4.setUser(user2);

        session3.save(userRoles1);
        session3.save(userRoles2);
        session3.save(userRoles3);
        session3.save(userRoles4);

        session3.getTransaction().commit();

        ProductType productType1 = new ProductType();
        productType1.setId(1);
        productType1.setTitle("Flat/Apartment");
        ProductType productType2 = new ProductType();
        productType2.setId(2);
        productType2.setTitle("House");

        ProductSize productSize1 = new ProductSize();
        productSize1.setId(1);
        productSize1.setTitle("1 Bed");
        ProductSize productSize2 = new ProductSize();
        productSize2.setId(2);
        productSize2.setTitle("2 Bed");
        ProductSize productSize3 = new ProductSize();
        productSize3.setId(3);
        productSize3.setTitle("3 Bed");
        ProductSize productSize4 = new ProductSize();
        productSize4.setId(4);
        productSize4.setTitle("4 Bed");
        ProductSize productSize5 = new ProductSize();
        productSize5.setId(5);
        productSize5.setTitle("5 Bed");

        ProductCategory productCategory1 = new ProductCategory();
        productCategory1.setId(1);
        productCategory1.setTitle("1 Room");
        ProductCategory productCategory2 = new ProductCategory();
        productCategory2.setId(2);
        productCategory2.setTitle("2 Room");
        ProductCategory productCategory3 = new ProductCategory();
        productCategory3.setId(3);
        productCategory3.setTitle("3 Room");

        Location location1 = new Location();
        location1.setId(1);
        location1.setLocationType("type1");
        location1.setSearchString("london1");
        location1.setPostCode("c1");
        Location location2 = new Location();
        location2.setId(2);
        location2.setLocationType("type2");
        location2.setSearchString("london2");
        location2.setPostCode("c2");
        Location location3 = new Location();
        location3.setId(3);
        location3.setLocationType("type3");
        location3.setSearchString("london3");
        location3.setPostCode("c3");

        Amenity amenity1 = new Amenity();
        amenity1.setId(1);
        amenity1.setTitle("Parking");
        Amenity amenity2 = new Amenity();
        amenity2.setId(2);
        amenity2.setTitle("Balcony/patio");
        Amenity amenity3 = new Amenity();
        amenity3.setId(3);
        amenity3.setTitle("Garden/roof terrace");
        Amenity amenity4 = new Amenity();
        amenity4.setId(4);
        amenity4.setTitle("Disabled access");
        Amenity amenity5 = new Amenity();
        amenity5.setId(5);
        amenity5.setTitle("Garage");

        Availability availability1 = new Availability();
        availability1.setId(1);
        availability1.setTitle("Daily");

        Availability availability2 = new Availability();
        availability2.setId(1);
        availability2.setTitle("Weekly");

        Availability availability3 = new Availability();
        availability3.setId(1);
        availability3.setTitle("Monthly");

        Stay stay1 = new Stay();
        stay1.setId(1);
        stay1.setTitle("No Limit");
        Stay stay2 = new Stay();
        stay2.setId(2);
        stay2.setTitle("1 day");
        Stay stay3 = new Stay();
        stay3.setId(3);
        stay3.setTitle("3 week");
        Stay stay4 = new Stay();
        stay4.setId(4);
        stay4.setTitle("1 month");

        Smoking smoking1 = new Smoking();
        smoking1.setId(1);
        smoking1.setTitle("No preference");
        Smoking smoking2 = new Smoking();
        smoking2.setId(2);
        smoking2.setTitle("No");

        Occupation occupation1 = new Occupation();
        occupation1.setId(1);
        occupation1.setTitle("No preference");
        Occupation occupation2 = new Occupation();
        occupation2.setId(2);
        occupation2.setTitle("Student");
        Occupation occupation3 = new Occupation();
        occupation3.setId(1);
        occupation3.setTitle("Professional");

        Pet pet1 = new Pet();
        pet1.setId(1);
        pet1.setTitle("No preference");
        Pet pet2 = new Pet();
        pet2.setId(2);
        pet2.setTitle("No");

        Product product = new Product();
        product.setUser(user1);
        product.setReferenceId(StringUtils.getProductReferenceId());
        product.setTitle("product1");
        product.setDescription("description1");
        product.setFirstName("firstn1");
        product.setLastName("lastn1");
        product.setCompanyName("company1");
        product.setPhone("01722123456");
        product.setProductType(productType2);
        product.setProductSize(productSize3);
        product.setProductCategory(productCategory1);
        product.setLocation(location2);
        product.setMinStay(stay1);
        product.setMaxStay(stay3);
        product.setSmoking(smoking2);
        product.setOccupation(occupation2);
        product.setPet(pet2);
        product.setImg("a.jpg");

        Image image1 = new Image();
        image1.setTitle("a.jpg");
        Image image2 = new Image();
        image2.setTitle("b.jpg");
        Image image3 = new Image();
        image3.setTitle("c.jpg");
        Image[] images = new Image[3];
        images[0] = image1;
        images[1] = image2;
        images[2] = image3;

        session.beginTransaction();
        session.save(productType1);
        session.save(productType2);
        session.save(productSize1);
        session.save(productSize2);
        session.save(productSize3);
        session.save(productSize4);
        session.save(productSize5);
        session.save(productCategory1);
        session.save(productCategory2);
        session.save(productCategory3);
        session.save(location1);
        session.save(location2);
        session.save(location3);
        session.save(amenity1);
        session.save(amenity2);
        session.save(amenity3);
        session.save(amenity4);
        session.save(amenity5);
        session.save(availability1);
        session.save(availability2);
        session.save(availability3);
        session.save(stay1);
        session.save(stay2);
        session.save(stay3);
        session.save(stay4);
        session.save(smoking1);
        session.save(smoking2);
        session.save(occupation1);
        session.save(occupation2);
        session.save(occupation3);
        session.save(pet1);
        session.save(pet2);
        session.save(product);
        if (images != null) {
            for (Image image : images) {
                image.setProductId(product.getId());
                session.save(image);
            }
        }

        Currency currency1 = new Currency();
        currency1.setTitle("");
        Currency currency2 = new Currency();
        currency2.setTitle("$");
        session.save(currency1);
        session.save(currency2);

        CurrencyUnit currencyUnit1 = new CurrencyUnit();
        currencyUnit1.setTitle("default");
        CurrencyUnit currencyUnit2 = new CurrencyUnit();
        currencyUnit2.setTitle("p");
        session.save(currencyUnit1);
        session.save(currencyUnit2);

        //add a default bid
        ProductBid bid = new ProductBid();
        bid.setReferenceId("abcd1234");
        bid.setUser(user2);
        bid.setProduct(product);
        bid.setCreatedOn(1234567);
        bid.setPrice(100);
        bid.setCurrency(currency1);
        bid.setCurrencyUnit(currencyUnit1);
        session.save(bid);

        Message message = new Message();
        message.setFrom(user2);
        message.setTo(user1);
        message.setProduct(product);
        message.setSubject("I need a room");

        session.save(message);

        MessageText messageText = new MessageText();
        messageText.setBody("What is the price of that room?");
        messageText.setUser(user2);
        messageText.setMessageId(message.getId());

        session.save(messageText);

        session.getTransaction().commit();
    } catch (Exception ex) {
        System.out.println(ex.toString());
    }
}

From source file:docreg.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*w ww  .j  a  va  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");
    PrintWriter out = response.getWriter();
    try {
        String path = "refresh_page.jsp";
        SessionFactory sf = HibernateUtil.getSessionFactory();
        Session ss = sf.openSession();
        Transaction tr = ss.beginTransaction();

        Speciality sp = new Speciality();
        sp.setSpecName(request.getParameter("spec_name"));
        ss.save(sp);

        Qualification qf = new Qualification();
        qf.setQualificationName(request.getParameter("qualification_name"));
        ss.save(qf);

        Addressdetails ad = new Addressdetails();
        ad.setLine1(request.getParameter("line1"));
        ad.setLine2(request.getParameter("line2"));
        ad.setState(request.getParameter("state"));
        ad.setCity(request.getParameter("city"));
        ad.setPincode(request.getParameter("pincode"));
        ss.save(ad);

        Login lo = new Login();
        lo.setUsername(request.getParameter("user_id"));
        lo.setPassword(request.getParameter("password"));
        lo.setRole("doctor");
        ss.save(lo);

        Doctor dc = new Doctor();
        dc.setDFirstname(request.getParameter("d_firstname"));
        dc.setDLastname(request.getParameter("d_lastname"));
        dc.setEmailId(request.getParameter("email_id"));
        dc.setContactnum(request.getParameter("Cont_num"));
        dc.setGender(request.getParameter("gender"));
        dc.setStatus("not_active");
        dc.setBirthDate(request.getParameter("birth_date"));
        dc.setAddressid(ad);
        dc.setQualificationId(qf);
        dc.setSpecialityId(sp);
        dc.setUserId(lo);
        ss.save(dc);

        tr.commit();

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

        out.println("success");
    }

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

    finally {
        out.close();
    }
}

From source file:createAccount.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from ww w  .  j a  v a  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()) {
        List allusers = list();

        String username = request.getParameter("new_username");
        String password = request.getParameter("new_password");
        SystemUser su = new SystemUser(allusers.size(), username, password);
        SessionFactory sf = HibernateUtil.getSessionFactory();
        Session session = sf.openSession();

        session.beginTransaction();

        if (userExists(su.getUsername()) == null) {
            int id = (int) session.save(su);
            su.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("Username already exists!");
        }
    }
}

From source file:addDRO.java

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

        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);
        tr.commit();

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

        path = "FailureDRO.jsp";
        RequestDispatcher rd = request.getRequestDispatcher(path);
        rd.forward(request, response);
    }
}

From source file:CriarProduto.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./* w ww  .  ja  v  a  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");
    try (PrintWriter out = response.getWriter()) {
        /* 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 CriarProduto</title>");
        out.println("</head>");
        out.println("<body>");
        out.println("<h1>Servlet CriarProduto at " + request.getContextPath() + "</h1>");
        out.println("</body>");
        out.println("</html>");

        Produto pteste = new Produto();
        pteste.setFabricante("pilot");
        pteste.setNome("bonina");
        pteste.setPreco(1);
        // pteste.setId(0); n~ precisa esta sendo gerado automaticamente

        //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(pteste);
        sessao.flush();

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