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

@Test(expected = MappingException.class)
public void TestDeleteException02() {
    Session session = sessionFctry.openSession();
    Transaction tx = null;//from  w  w  w. j av  a  2s. com
    Integer idTemporaryStudent = null;

    /***********************/
    /*dodaj studenta do db*/
    /**********************/
    tx = session.beginTransaction();

    Student temporaryStudent = new Student("Karol", "Marzyciel", "Malinowa 23");
    idTemporaryStudent = (Integer) session.save(temporaryStudent);

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

    /****************************/
    /*usu nowododanego studenta*/
    /****************************/
    session = sessionFctry.openSession();
    tx = session.beginTransaction();

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

    tx.commit();

    session.close();

    /******************************/
    /*sprbuj pobra tego studenta*/
    /******************************/
    session = sessionFctry.openSession();
    tx = session.beginTransaction();

    Student poszukiwany = (Student) session.get(Student.class, idTemporaryStudent); //to powinno wyrzuci null

    assertNull(poszukiwany);

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

}

From source file:SalvarVinho.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from   ww w.j  a va  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");
    try (PrintWriter out = response.getWriter()) {
        /* TODO output your page here. You may use following sample code. */

        try {
            Vinho vin = new Vinho();

            vin.setNome(request.getParameter("nome"));
            vin.setUva(request.getParameter("uva"));

            String v = request.getParameter("ano");
            if (v != null) {
                Integer ano = Integer.parseInt(v);
                vin.setAno_safra(ano);
            }

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

            Transaction tx = sessao.beginTransaction();

            sessao.save(vin);
            sessao.flush();

            tx.commit();

            sessao.close();

            out.println("Registro gravado com sucesso");
        } catch (Exception e) {
            out.println("Erro ao gravar: " + e.getMessage());
        }
    }
}

From source file:$.DefaultDAO.java

License:Open Source License

/**
     * Creates a new entry in the datastorage with data from provided entity
     *//from   w w w.jav  a 2s.  c o  m
     * @param entity entity information to save
     *
      * @return ID of the newly created entity
      */
    public <ENTITY extends IdentifiedEntityInterface> Long create(ENTITY entity) {
        if (entity == null) {
            throw new IllegalArgumentException("Invalid entity provided:[NULL]");
        }

        if (entity.getId() != null) {
            entity.setId(null);
        }

        Session session = getSession();

        return (Long) session.save(entity);
    }

From source file:a.A.java

/**
 * @param args the command line arguments
 */// w  w w .ja v  a2 s.c  o  m
public static void main(String[] args) {
    // TODO code application logic here
    String URL = "jdbc:mysql://localhost/MyBD";
    String USER = "root";
    String PASSWORD = "root";
    String DRIVER_CLASS = "com.mysql.jdbc.Driver";

    try {

        Class.forName(DRIVER_CLASS);
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }
    Connection connection = null;
    try {

        connection = DriverManager.getConnection(URL, USER, PASSWORD);
    } catch (SQLException e) {
        System.out.println("ERROR: Unable to Connect to Database.");
    }

    Configuration cfg = new Configuration();
    cfg.configure("a/hibernate.cfg.xml");//populates the data of the configuration file  
    //creating seession factory object  
    ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(cfg.getProperties())
            .build();
    SessionFactory factory = cfg.buildSessionFactory(serviceRegistry);

    String line;
    String csv = "C:\\Users\\hp\\Desktop\\GeoLiteCity-Location.csv";
    try (BufferedReader br = new BufferedReader(new FileReader(csv))) {

        count = 0;
        City e1 = new City();

        while ((line = br.readLine()) != null) {
            if (count > 1) {
                Session session = factory.openSession();
                // creating transaction object  
                Transaction t = session.beginTransaction();
                System.out.println(line);
                String[] s = line.split("[,]");
                System.out.println(s[0]);
                System.out.println(s[1]);
                System.out.println(Float.parseFloat(s[5]));
                System.out.println(Float.parseFloat(s[6]));
                e1.setId(Integer.parseInt(s[0]));
                e1.setName(s[1]);
                e1.setC(s[3]);
                e1.setlat(Float.parseFloat(s[5]));
                e1.setlon(Float.parseFloat(s[6]));
                session.save(e1);
                t.commit();//transaction is commited  
                session.close();
            } else {
                count++;
            }
        }

        //                Session currentSession = factory.openSession();  
        //                List <City> list=null;
        //    //  while(list==null){
        //    list = currentSession.createCriteria(City.class)  
        //                             .add(Restrictions.eq("Name", "NL"))  
        //                             .list();
        //      for(int i=0;i<list.size();i++){
        //          
        //    System.out.println(list.get(i));
        //            }

    } catch (IOException e) {
        e.printStackTrace();
    }
    String a, b;
    float lats = 0;
    float lats2 = 0;
    float longs = 0;
    float longs2 = 0;
    System.out.print("Enter name of first city");
    Distance d1 = new Distance();

    Scanner scanner = new Scanner(System.in);
    a = scanner.nextLine();
    a = "\"" + a + "\"";
    System.out.print("Enter name of second city");
    //Scanner scanner=new Scanner(System.in);
    b = scanner.nextLine();
    b = "\"" + b + "\"";
    Transaction tx;

    Session session = factory.openSession();
    try {
        // int index=0;
        tx = session.beginTransaction();
        List employees = session.createQuery("FROM City").list();
        for (Iterator iterator = employees.iterator(); iterator.hasNext();) {
            City c = (City) iterator.next();

            if (a.contentEquals(c.getC())) {

                System.out.print("Name: " + c.getName());
                System.out.print(" City: " + c.getC());
                lats = c.getlon();
                longs = c.getlat();
                System.out.print("  Longitude: " + c.getlon());
                System.out.println("  Latitude: " + c.getlat());
                break;
            }
        }
        List<String> citynames = new ArrayList<String>();
        List<Double> doubleList = new ArrayList<Double>();
        System.out.println("Enter number of cities");
        Scanner s = new Scanner(System.in);
        int num = Integer.parseInt(s.nextLine());

        Distance obj = new Distance();
        int i = 0;
        for (Iterator iterator = employees.iterator(); iterator.hasNext();) {
            City c = (City) iterator.next();
            if (i < num) {
                doubleList.add(obj.GreatD(lats, longs, c.getlat(), c.getlon()));
                citynames.add(c.getC());
                i++;
            } else {
                //get max value from list
                Integer j = 0, maxIndex = -1;
                Double max = null;
                for (Double x : doubleList) {
                    if ((x != null) && ((max == null) || (x > max))) {
                        max = x;
                        maxIndex = j;
                    }
                    j++;
                }
                double dare = obj.GreatD(lats, longs, c.getlat(), c.getlon());
                if (dare < max) {
                    citynames.set(maxIndex, c.getC());
                    doubleList.set(maxIndex, dare);
                    //list
                }
            }
            // For first n values add to list

        }
        for (int k = 0; k < citynames.size(); k++) {
            System.out.println(citynames.get(k));
        }
        //         

        int check = 0;
        for (Iterator iterator = employees.iterator(); iterator.hasNext();) {
            City c = (City) iterator.next();

            if (check == 2) {
                break;
            } else {
                if (b.contentEquals(c.getC())) {

                    System.out.print("Name: " + c.getName());
                    System.out.print(" City: " + c.getC());
                    longs = c.getlon();
                    lats = c.getlat();
                    System.out.print("  Longitude: " + c.getlon());
                    System.out.println("  Latitude: " + c.getlat());
                    check++;
                }
                if (a.contentEquals(c.getC())) {

                    System.out.print("Name: " + c.getName());
                    System.out.print(" City: " + c.getC());
                    longs2 = c.getlon();
                    lats2 = c.getlat();
                    System.out.print("  Longitude: " + c.getlon());
                    System.out.println("  Latitude: " + c.getlat());
                    check++;
                }
            }
        }
        System.out.println(d1.GreatD(lats, longs, lats2, longs2));

        tx.commit();
        return;
    } catch (Exception e) {
        e.printStackTrace();
    }

}

From source file:academy.util.HibernateUtilTest.java

public Long addToDatabase(Object object) {
    final Session session = util.getSessionFactory().openSession();
    Transaction transaction = session.beginTransaction();
    Long id = null;/*  ww  w  . java2 s.c o  m*/
    try {
        id = (Long) session.save(object);
    } catch (HibernateException e) {
        transaction.rollback();
    } finally {
        session.flush();
        transaction.commit();
        session.close();
    }
    return id;
}

From source file:acceptance.hibernate.HibernateReferenceTest.java

License:Open Source License

/**
 * Create the object within a Hibernate session and persist it.
 *///  w ww .j  a  va 2  s. c o  m
private Division setupPersistentDivision() {
    final Session session = getSessionFactory().getCurrentSession();
    session.beginTransaction();
    final Division div = new Division("Div1");
    final Department dep = new Department("Dep1", div);
    final Site site = new Site("Site1");
    /*
     * This save is necessitated by the fact that Hibernate's transitive persistence is
     * depth-first and does not do a full graph analysis. Therefore it would be possible for
     * Hibernate to try to save the person record before the site record, which would throw
     * an error if the person.site FK is non-nullable.
     */
    session.save(site);
    new Person("Tom", dep, site);
    session.save(div);
    session.flush();
    session.getTransaction().commit();
    return div;
}

From source file:accesobd.AccesoRoles.java

License:BSD License

/**
 * Mtodo para actualizar (agregar o modificar) un rol.
 * @param rol La estructura que representa el rol.
 * @param tipoMantenimiento El tipo de mantenimiento (AGREGAR, MODIFICAR, ELIMINAR).
 * @return // w ww . j a  va2 s  .c om
 */
public Respuesta actualizarRol(AdmRol rol, TipoMantenimiento tipoMantenimiento) {
    Respuesta res = new Respuesta();

    boolean huboError = false;

    Session sesion;
    Transaction tx = null;

    sesion = HibernateUtil.getSessionFactory().openSession();

    // Inicia la transaccin.
    tx = sesion.beginTransaction();
    try {
        String operacionHecha = null;

        if (tipoMantenimiento == TipoMantenimiento.AGREGAR) {
            sesion.save(rol);
            operacionHecha = "agregado";
        } else if (tipoMantenimiento == TipoMantenimiento.MODIFICAR) {
            sesion.update(rol);
            operacionHecha = "modificado";
        } else if (tipoMantenimiento == TipoMantenimiento.ELIMINAR) {
            sesion.delete(rol);
            operacionHecha = "eliminado";
        }

        tx.commit(); // Hace commit a la trasaccin.

        res.setResultado(true);
        res.setMensaje(String.format("Rol %s exitosamente", operacionHecha));
    } catch (Exception ex) {
        huboError = true;

        res.setMensaje("Error al realizar la operacin en base de datos. No se pudo actualizar el sistema.");
        res.setMensajeError(ex.toString());
    } finally {
        if (huboError) {
            tx.rollback();
            res.setResultado(false);
        }
        sesion.close();
    }

    return res;
}

From source file:accesobd.AccesoRolesVistas.java

License:BSD License

/**
 * Mtodo para actualizar (agregar o modificar) un rol-vista.
 *
 * @param rolVista La estructura que representa el rol-vista
 * @param tipoMantenimiento El tipo de mantenimiento (AGREGAR, MODIFICAR,
 * ELIMINAR)./*from  ww  w .j a  v a2s  .c o m*/
 * @return
 */
public Respuesta actualizarVista(AdmRolVista rolVista, TipoMantenimiento tipoMantenimiento) {
    Respuesta res = new Respuesta();

    boolean huboError = false;

    Session sesion;
    Transaction tx;

    sesion = HibernateUtil.getSessionFactory().openSession();

    // Inicia la transaccin.
    tx = sesion.beginTransaction();
    try {
        String operacionHecha = null;

        if (tipoMantenimiento == TipoMantenimiento.AGREGAR) {
            sesion.save(rolVista);
            operacionHecha = "agregada";
        } else if (tipoMantenimiento == TipoMantenimiento.MODIFICAR) {
            throw new Exception("Esta operacin no est soportada para esta entidad.");
        } else if (tipoMantenimiento == TipoMantenimiento.ELIMINAR) {
            sesion.delete(rolVista);
            operacionHecha = "eliminada";
        }

        tx.commit(); // Hace commit a la trasaccin.

        res.setResultado(true);
        res.setMensaje(String.format("Rol-Vista %s exitosamente", operacionHecha));
    } catch (Exception ex) {
        huboError = true;

        res.setMensaje("Error al realizar la operacin en base de datos. No se pudo actualizar el sistema.");
        res.setMensajeError(ex.toString());
    } finally {
        if (huboError) {
            tx.rollback();
            res.setResultado(false);
        }
        sesion.close();
    }

    return res;
}

From source file:accesobd.AccesoVistas.java

License:BSD License

/**
 * Mtodo para actualizar (agregar o modificar) una vista.
 * @param vista La estructura que representa el rol.
 * @param tipoMantenimiento El tipo de mantenimiento (AGREGAR, MODIFICAR, ELIMINAR).
 * @return //from   w  w w.j a v a2 s .c o m
 */
public Respuesta actualizarVista(AdmVista vista, TipoMantenimiento tipoMantenimiento) {
    Respuesta res = new Respuesta();

    boolean huboError = false;

    Session sesion;
    Transaction tx;

    sesion = HibernateUtil.getSessionFactory().openSession();

    // Inicia la transaccin.
    tx = sesion.beginTransaction();
    try {
        String operacionHecha = null;

        if (tipoMantenimiento == TipoMantenimiento.AGREGAR) {
            sesion.save(vista);
            operacionHecha = "agregada";
        } else if (tipoMantenimiento == TipoMantenimiento.MODIFICAR) {
            sesion.update(vista);
            operacionHecha = "modificada";
        } else if (tipoMantenimiento == TipoMantenimiento.ELIMINAR) {
            sesion.delete(vista);
            operacionHecha = "eliminada";
        }

        tx.commit(); // Hace commit a la trasaccin.

        res.setResultado(true);
        res.setMensaje(String.format("Vista %s exitosamente", operacionHecha));
    } catch (Exception ex) {
        huboError = true;

        res.setMensaje("Error al realizar la operacin en base de datos. No se pudo actualizar el sistema.");
        res.setMensajeError(ex.toString());
    } finally {
        if (huboError) {
            tx.rollback();
            res.setResultado(false);
        }
        sesion.close();
    }

    return res;
}

From source file:acc_r3_javier_gonzalez.Modificaciones.java

/**
 * Metodo para insertar una cerveza.//w ww . ja va2  s. c o m
 * @param cerve 
 */
public static void insertaCerve(R3Cerveza cerve) {
    Session s = Conexion.getSession();
    Conexion.transacciona();

    s.save(cerve);

    Conexion.commit();
    Conexion.desconecta();
}