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:action.DocumentAction.java

public String addDocument() throws Exception {
    Session session = HibernateUtil.getSessionFactory().openSession();
    try {//w  w w.ja  v a2 s .c o m
        document.setCreated_at(new Date());
        document.setUpdated_at(new Date());
        session.beginTransaction();
        session.save(document);
        session.getTransaction().commit();
        this.setDocumentList((List<Document>) session.createCriteria(Document.class).list());
    } catch (Exception e) {
        System.err.println("Error creating User :" + e.getMessage());
        session.getTransaction().rollback();
        return ERROR;
    } finally {
        if (session.isOpen()) {
            session.close();
        }
    }
    return SUCCESS;

}

From source file:Action.OrderManagement.java

public String addOrder() throws NullPointerException {
    Session s = HibernateUtil.getSession();
    Transaction t = s.beginTransaction();

    Company_Details company_Details;//from   w w w .  ja  v a 2 s .c  o m
    Query q1 = s.createQuery(" from Company_Details where companyName='" + getCompanyName() + "'");
    List<Company_Details> data1 = q1.list();
    company_Details = new Company_Details(0, getCompanyName(), getStreet1(), getStreet2(), getCity(),
            getProvince(), getPincode(), getEmailId(), getCompanyHead(), getContactNo1(), getContactNo2());

    if (data1.isEmpty()) {
        s.save(company_Details);
        System.out.println("sssss");
    }

    setNewMaterialRequired("  Pieces ." + "Material Required for Order  - 1. " + getName() + "  "
            + getQuantity() + "  Pieces   2. " + getName2() + "  " + getQuantity2());
    Order_Details order_Details;
    order_Details = new Order_Details(0, getOrderDescription(), getContactPerson(), "Pending", 0, 0,
            getNewMaterialRequired(), company_Details);
    s.save(order_Details);

    if (getName2().isEmpty()) {
    } else {
        Product_Details product_Details;
        product_Details = new Product_Details(0, getName(), getQuantity(), getRateFixed(), getDeliveryDate(),
                order_Details);
        s.save(product_Details);

        Product_Processing product_processing11;
        product_processing11 = new Product_Processing(0, 0, "Process 1", product_Details);
        s.save(product_processing11);
        Product_Processing product_processing12;
        product_processing12 = new Product_Processing(0, 0, "Process 2", product_Details);
        s.save(product_processing12);
        Product_Processing product_processing13;
        product_processing13 = new Product_Processing(0, 0, "Process 3", product_Details);
        s.save(product_processing13);
        Product_Processing product_processing14;
        product_processing14 = new Product_Processing(0, 0, "Process 4", product_Details);
        s.save(product_processing14);
        Product_Processing product_processing15;
        product_processing15 = new Product_Processing(0, 0, "Process 5", product_Details);
        s.save(product_processing15);
    }

    if (getName2().isEmpty()) {
    } else {
        Product_Details product_Details2;
        product_Details2 = new Product_Details(0, getName2(), getQuantity2(), getRateFixed2(),
                getDeliveryDate2(), order_Details);
        s.save(product_Details2);

        Product_Processing product_processing21;
        product_processing21 = new Product_Processing(0, 0, "Process 1", product_Details2);
        s.save(product_processing21);
        Product_Processing product_processing22;
        product_processing22 = new Product_Processing(0, 0, "Process 2", product_Details2);
        s.save(product_processing22);
        Product_Processing product_processing23;
        product_processing23 = new Product_Processing(0, 0, "Process 3", product_Details2);
        s.save(product_processing23);
        Product_Processing product_processing24;
        product_processing24 = new Product_Processing(0, 0, "Process 4", product_Details2);
        s.save(product_processing24);
        Product_Processing product_processing25;
        product_processing25 = new Product_Processing(0, 0, "Process 5", product_Details2);
        s.save(product_processing25);
    }
    /*  if(Name3.isEmpty()){        // To be corrected
    } else {
    Product_Details product_Details3;
    product_Details3 = new Product_Details( 0, Name3, Quantity3,rateFixed3,deliveryDate3,order_Details);
    s.save(product_Details3);
    Product_Details product_Details4;
    product_Details4 = new Product_Details( 0, Name4, Quantity4,rateFixed4,deliveryDate4,order_Details);
    s.save(product_Details4);
    Product_Details product_Details5;
    product_Details5 = new Product_Details( 0, Name5, Quantity5,rateFixed5,deliveryDate5,order_Details);
    s.save(product_Details5);
      }*/

    t.commit();

    return "success";
}

From source file:Action.StockManagement.java

public String addStock() throws NullPointerException {
    Session s = HibernateUtil.getSession();
    Transaction t = s.beginTransaction();

    Supplier_Details supplier_Details;
    Query q1 = s.createQuery(" from Supplier_Details where SupplierId='" + getSupplierId() + "'");
    List<Supplier_Details> data1 = q1.list();
    supplier_Details = new Supplier_Details(getSupplierId(), getSupplierName(), getStreet1(), getStreet2(),
            getCity(), getProvince(), getPincode(), getEmailId(), getContactNo1(), getContactNo2());

    if (data1.isEmpty()) {
        s.save(supplier_Details);
    }//  www .  java  2  s  .c  o  m

    getReq().setAttribute(getSupplierName(), getResult());

    t.commit();
    Session s1 = HibernateUtil.getSession();
    Transaction t1 = s1.beginTransaction();
    Item_History item_History;
    Query q = s1.createQuery(" from Current_Stock where itemId='" + getItemId() + "'");
    List<Current_Stock> data = q.list();
    if (data.isEmpty()) {
        item_History = new Item_History(0, getName(), getCompanyName(), getQuantity(), getType(),
                getDescription(), getCostPerPiece(), getDateOfPurchase(), supplier_Details);
        Current_Stock current_Stock = new Current_Stock(getItemId(), getName(), getQuantity(),
                getCostPerPiece(), getType(), getDescription());
        s1.save(item_History);
        s1.save(current_Stock);
    } else {
        item_History = new Item_History(0, getName(), getCompanyName(), getQuantity(), getType(),
                getDescription(), getCostPerPiece(), getDateOfPurchase(), supplier_Details);
        Current_Stock current_Stock = (Current_Stock) s1.get(Current_Stock.class, getItemId());
        current_Stock.setQuantity(getQuantity() + current_Stock.getQuantity());
        double newCost = ((current_Stock.getCostPerPiece() * current_Stock.getQuantity()
                + getQuantity() * getCostPerPiece()) / current_Stock.getQuantity() + getQuantity());
        current_Stock.setCostPerPiece(newCost);
        s1.save(item_History);
        s1.save(current_Stock);

    }

    getReq().setAttribute(getSupplierName(), getResult());

    t1.commit();

    return "success";
}

From source file:Activity.activitySetter.java

public static void createActivity(String activityName, Category category) {
    Session session = HibernateUtil.getSessionFactory().openSession();
    session.beginTransaction();//from   www.  ja v  a2 s.c  om
    Activity act = new Activity();
    act.setActivityName(activityName);
    act.setCategory(category);
    session.save(act);
    session.getTransaction().commit();

}

From source file:Activity.activitySetter.java

public static void createActivityReport(Activity activity, String activityDescription,
        Timestamp activityStartTime, Timestamp activityEndTime, Integer ActivityDuration) {
    Session session = HibernateUtil.getSessionFactory().openSession();
    session.beginTransaction();//from   www .j a va  2s  .  c o m
    ActivityReport actRep = new ActivityReport();
    actRep.setActivity(activity);
    actRep.setActivityDescription(activityDescription);
    actRep.setActivityStartTime(activityStartTime);
    actRep.setActivityEndTime(activityEndTime);
    actRep.setActivityDuration(ActivityDuration);
    session.save(actRep);
    session.getTransaction().commit();

}

From source file:addCE.ExcelReader.java

public static void main(String args[]) {
    ExcelReader creader = new ExcelReader();
    creader.read();/*from   w w  w  .  jav  a2s  .  co  m*/

    SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
    Session session = sessionFactory.openSession();

    int id = 0;
    for (ArrayList<String> l1 : creader.attendees) {
        if (l1.get(0) != "None") {
            for (String n : l1) {
                System.out.print(n + " ");
            }
            System.out.println();

            Attendee attendee = new Attendee();
            attendee.setId(id);
            attendee.setFirstName(l1.get(0));
            attendee.setLastName(l1.get(1));
            attendee.setProfession(l1.get(2));
            attendee.setLicenseNum(l1.get(3));
            attendee.setCountry(l1.get(4));
            attendee.setAccredDate(l1.get(5));
            attendee.setCreditType(l1.get(6));
            attendee.setNumCredits(l1.get(7));
            attendee.setEmailAddr(l1.get(8));
            attendee.setCertCode(creader.certcode());

            session.beginTransaction();
            session.save(attendee);
            session.getTransaction().commit();
            id += 1;
        }
    }
    System.out.println(creader.attendees.size());

    session.close();

}

From source file:admin.AddFlightHandler.java

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String company = request.getParameter("companyId");
    String flightName = request.getParameter("flightName");
    String source = request.getParameter("sourceId");
    String destination = request.getParameter("destinationId");
    String dayId[] = request.getParameterValues("dayId");
    String departure = request.getParameter("departureTime") + ":00";
    String arrival = request.getParameter("arrivalTime") + ":00";
    String fare1 = request.getParameter("fare1");
    String fare2 = request.getParameter("fare2");
    String fare3 = request.getParameter("fare3");
    String seats1 = request.getParameter("seats1");
    String seats2 = request.getParameter("seats2");
    String seats3 = request.getParameter("seats3");

    //Flight Master Data to set
    CompanyMaster companyId = new CompanyMaster();
    AerodrumMaster sourceId = new AerodrumMaster();
    AerodrumMaster destinationId = new AerodrumMaster();
    Time departureTime;//from w  w w  .  j a  va 2s .  c  om
    Time arrivalTime;
    List<FlightFareMap> ffm = new ArrayList<>();
    List<DayMaster> days = new ArrayList<>();

    try {
        //Setting internal flight Master data
        companyId.setCompanyId(Integer.parseInt(company));
        sourceId.setAerodrumId(Integer.parseInt(source));
        destinationId.setAerodrumId(Integer.parseInt(destination));
        departureTime = Time.valueOf(departure);
        arrivalTime = Time.valueOf(arrival);

        //ClassMaster Object
        ClassMaster c1 = new ClassMaster();
        ClassMaster c2 = new ClassMaster();
        ClassMaster c3 = new ClassMaster();
        //Creating FlightFareMap objects
        //First Class
        c1.setClassId(1);
        FlightFareMap ffm1 = new FlightFareMap();
        ffm1.setClassId(c1);
        ffm1.setFare(Integer.parseInt(fare1));
        ffm1.setNumberOfSeats(Integer.parseInt(seats1));

        //Business Class
        c2.setClassId(2);
        FlightFareMap ffm2 = new FlightFareMap();
        ffm2.setClassId(c2);
        ffm2.setFare(Integer.parseInt(fare2));
        ffm2.setNumberOfSeats(Integer.parseInt(seats2));

        //Economy Class
        c3.setClassId(3);
        FlightFareMap ffm3 = new FlightFareMap();
        ffm3.setClassId(c3);
        ffm3.setFare(Integer.parseInt(fare3));
        ffm3.setNumberOfSeats(Integer.parseInt(seats3));

        //Adding the FlightFareMap objects to the list of flightMaster
        ffm.add(ffm1);
        ffm.add(ffm2);
        ffm.add(ffm3);

        //DayMaster Object
        for (String day : dayId) {
            DayMaster d = new DayMaster();
            d.setDayId(Integer.parseInt(day));
            //Adding day object to the list of days
            days.add(d);
        }

        //Creating FlightMasterObject and Setting All the Properties
        FlightMaster flight = new FlightMaster();
        flight.setFlightName(flightName);
        flight.setCompanyId(companyId);
        flight.setSourceId(sourceId);
        flight.setDestinationId(destinationId);
        flight.setDepartureTime(departureTime);
        flight.setArrivalTime(arrivalTime);
        flight.setFare(ffm);
        flight.setDays(days);

        //Storing the flight and ffm1,ffm2,ffm3 objects into the database
        Session session = HibernateDAOLayer.getSession();
        Transaction transaction = session.beginTransaction();
        session.save(ffm1);
        session.save(ffm2);
        session.save(ffm3);
        session.save(flight);
        transaction.commit();
    } catch (Exception e) {
        String message = "Error : " + e.getMessage();
        request.setAttribute("emessage", message);
        RequestDispatcher dispatcher = request.getRequestDispatcher("addflight.jsp");
        dispatcher.forward(request, response);
    }
    String message = "Flight " + flightName + " Added Successfully !!!";
    request.setAttribute("message", message);
    RequestDispatcher dispatcher = request.getRequestDispatcher("addflight.jsp");
    dispatcher.forward(request, response);
}

From source file:administracion.actions.GestorOperacionesDatosRestaurante.java

public int actualizarNumeroMesas(int numeroMesasInicial, int numeroMesasNuevo) {

    int resultadoOperacion = 0;
    int diferencia = 0;
    Session sesion = null;
    try {/*from w w w  .  jav a 2 s  . c  o  m*/
        HibernateUtil hb = new HibernateUtil();
        sesion = hb.getSessionFactory().openSession();
        sesion.beginTransaction();

        if (numeroMesasNuevo > numeroMesasInicial) { //En este caso queremos ampliar el numero de mesas
            diferencia = numeroMesasNuevo - numeroMesasInicial; //Obtenemos la diferencia

            //Obtenemos el numero de mesas total. Teniendo en cuenta las activas + las no activas (si las hay)
            String sql = "SELECT numero_mesa,estado_mesa,activo FROM mesa";
            SQLQuery query = sesion.createSQLQuery(sql).addEntity(Mesa.class);
            int numeroMesasTotal = (int) query.list().size();

            for (int i = numeroMesasInicial + 1; i <= numeroMesasNuevo; i++) { //Itreamos desde el mayor numero de mesa activo actualmente hasta el numero de mesas final que queremos                   
                if (numeroMesasTotal > i) { //Quiere decir que la mesa ya existia pero estaba deshabilitada                       
                    String sql1 = "UPDATE mesa SET activo = true WHERE numero_mesa = " + i; //Actualizamos su estado
                    SQLQuery query1 = sesion.createSQLQuery(sql1);
                    query1.executeUpdate();
                } else { //La mesa no exite y la creamos                 
                    Mesa mesa = new Mesa(); //Creamos la mesa
                    mesa.setNumero(i);
                    mesa.setEstado(ESTADO_MESA);
                    mesa.setActivo(true);
                    sesion.save(mesa); //Hacemos el INSERT
                }
            }
            sesion.getTransaction().commit();
            resultadoOperacion = OPERACION_SUCCESS;

        } else { //En este caso queremos reducir el numero de mesas
            List<Mesa> listaMesas = obtenerListadoMesas(); //Obtenemos el listado de mesas (nos interesa para ver el estado)
            boolean reducir = true; //Indica si podemos realizar la operacion para reducir el numero de mesas          
            diferencia = numeroMesasInicial - numeroMesasNuevo; //Numero de mesas que queremos reducir
            for (int i = numeroMesasInicial - 1; i >= numeroMesasNuevo; i--) { //Iteremos por las mesas que queremos desactivar
                if (!listaMesas.get(i).getEstado().equals(ESTADO_MESA)) { //Si la mesa no esta libre
                    reducir = false; //NO PERMITIMOS LA OPERACION
                    resultadoOperacion = OPERACION_NO_POSIBLE;
                    break;
                }
            }
            if (reducir) { //Si todas las mesas que queremos desactivar estan libres
                for (int i = numeroMesasInicial - 1; i >= numeroMesasNuevo; i--) { //Las recorremos y las desactivamos
                    String sql = "UPDATE mesa SET activo = false WHERE numero_mesa = " + (i + 1);
                    SQLQuery query = sesion.createSQLQuery(sql);
                    query.executeUpdate();
                }
                sesion.getTransaction().commit();
                resultadoOperacion = OPERACION_SUCCESS;
            }
        }
    } catch (HibernateException e) {
        System.out.println("Error en la conexion con la base de datos: " + e);
        throw e;
    } catch (Exception e) {
        resultadoOperacion = OPERACION_ERROR;
        System.out.println("Error actualizar numero de mesas: " + e);
    } finally {
        if (sesion != null) {
            sesion.close();
        }
    }

    return resultadoOperacion;
}

From source file:AdminSystemClasses.AtmDB.java

public static BankATM addAtm(ATMaddmoddel atm) throws Exception {

    Session sf = DB.getSession();
    Transaction tx = sf.beginTransaction();

    Criteria cr = sf.createCriteria(BankATM.class);
    cr.add(Restrictions.eq("id", atm.getAtmId()));

    if (cr.list().isEmpty()) {
        BankBranch bb = (BankBranch) sf.load(BankBranch.class, atm.getBranchid());
        BankATM myatm = new BankATM();
        myatm.setId(atm.getAtmId());/*from  w  w w . ja  v  a2s .c  om*/
        myatm.setBankbranch(bb);
        myatm.setTill(atm.getTill());
        sf.save(myatm);
        tx.commit();
        return myatm;
    }

    return null;
}

From source file:aes.pica.touresbalon.touresbalonproductosws.servicios.Services.java

public com.touresbalon.productostouresbalon.TipoGestionCampaniaResponse gestionCampaniaProducto(
        com.touresbalon.productostouresbalon.TipoAccion tipoOperacion,
        com.touresbalon.productostouresbalon.Campania campania) throws GestionCampaniaProductoFault_Exception {

    Session sessionProductos;
    Transaction txProductos;/*from  w  ww  . j a va2  s. c o m*/

    sessionProductos = ProductosHU.getSessionFactory().getCurrentSession();
    txProductos = sessionProductos.beginTransaction();

    String sqlQuery;
    Query q = null;
    int idcamp;
    com.touresbalon.productostouresbalon.TipoGestionCampaniaResponse respuesta = new com.touresbalon.productostouresbalon.TipoGestionCampaniaResponse();
    //        if (null!=tipoOperacion  )
    switch (tipoOperacion) {
    case ADICIONAR: {
        try {
            aes.pica.touresbalon.touresbalonproductosws.entidades.productos.Campanias camp = new aes.pica.touresbalon.touresbalonproductosws.entidades.productos.Campanias();
            aes.pica.touresbalon.touresbalonproductosws.entidades.productos.Producto prod = new aes.pica.touresbalon.touresbalonproductosws.entidades.productos.Producto();
            prod.setIdProducto(campania.getIdProducto().getIdProducto());
            camp.setProducto(prod);
            camp.setFechaInicio(toDate(campania.getFechaInicioCampania()));
            camp.setFechaFin(toDate(campania.getFechaFinCampania()));
            sessionProductos.save(camp);
            if (camp.getIdCampania() > 0) {
                respuesta.setRespuesta(RespuestaGenerica.OK);
                respuesta.setIdCampania(camp.getIdCampania());
            } else {
                respuesta.setRespuesta(RespuestaGenerica.KO);
            }
            txProductos.commit();
        } catch (Exception e) {
            System.out.println("Error al Crear la Campaa: " + e.getMessage());
            txProductos.rollback();
        }
        break;
    }
    case MODIFICAR:

        List<aes.pica.touresbalon.touresbalonproductosws.entidades.productos.Campanias> lstcamp;
        lstcamp = new ArrayList<>();

        try {
            idcamp = Integer.valueOf(campania.getIdProducto().getEspectaculo());
        } catch (Exception e) {
            idcamp = 0;
        }

        try {
            sqlQuery = "from Campanias where idCampania = :idcampana";
            q = sessionProductos.createQuery(sqlQuery).setParameter("idcampana", idcamp);
            lstcamp = q.list();
        } catch (Exception e) {
            System.out.println("Error al Consultarla campaa: " + e.getMessage());
        }

        if (lstcamp.size() > 0) {

            aes.pica.touresbalon.touresbalonproductosws.entidades.productos.Campanias camp = new aes.pica.touresbalon.touresbalonproductosws.entidades.productos.Campanias();
            aes.pica.touresbalon.touresbalonproductosws.entidades.productos.Producto prod = new aes.pica.touresbalon.touresbalonproductosws.entidades.productos.Producto();
            prod.setIdProducto(campania.getIdProducto().getIdProducto());
            camp.setProducto(prod);
            camp.setIdCampania(idcamp);
            camp.setFechaInicio(toDate(campania.getFechaInicioCampania()));
            camp.setFechaFin(toDate(campania.getFechaFinCampania()));
            try {
                sessionProductos.clear();
                sessionProductos.update(camp);
                if (camp.getIdCampania() > 0) {
                    respuesta.setRespuesta(RespuestaGenerica.OK);
                } else {
                    respuesta.setRespuesta(RespuestaGenerica.KO);
                }
                txProductos.commit();
            } catch (Exception e) {
                System.out.println("Error al actualizar campaa: " + e.getMessage());
                txProductos.rollback();
            }

        } else {
            respuesta.setRespuesta(RespuestaGenerica.KO);
        }
        break;
    case ELIMINAR: {

        aes.pica.touresbalon.touresbalonproductosws.entidades.productos.Campanias camp = new aes.pica.touresbalon.touresbalonproductosws.entidades.productos.Campanias();
        List<aes.pica.touresbalon.touresbalonproductosws.entidades.productos.Campanias> lstcampa;

        try {
            idcamp = Integer.valueOf(campania.getIdProducto().getEspectaculo());

        } catch (Exception e) {
            idcamp = 0;
        }

        try {
            sqlQuery = "from Campanias where idCampania = :idcampana";
            q = sessionProductos.createQuery(sqlQuery).setParameter("idcampana", idcamp);
            lstcampa = q.list();
            if (lstcampa.size() > 0) {

                sessionProductos.clear();
                camp.setIdCampania(idcamp);
                sessionProductos.delete(camp);
                if (camp.getIdCampania() > 0) {
                    respuesta.setRespuesta(RespuestaGenerica.OK);
                } else {
                    respuesta.setRespuesta(RespuestaGenerica.KO);
                }
                txProductos.commit();
            } else {
                respuesta.setRespuesta(RespuestaGenerica.KO);
            }
        } catch (Exception e) {
            System.out.println("No se pudo borrar la campaa: " + e.getMessage());
            txProductos.rollback();
        }
        break;
    }
    default:
        respuesta.setRespuesta(RespuestaGenerica.KO);
        break;
    }

    if (sessionProductos.isOpen()) {
        sessionProductos.close();
    }
    return respuesta;
}