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:beans.Driver.java

public static void main(String[] args) {
    Student s = new Student();
    s.setId(4);/*from  www . j  a  v a 2s .com*/
    s.setName("Amjad");

    try {

        Configuration cf = new Configuration();
        cf.configure("xml/hibernate.cfg.xml");
        SessionFactory sf = cf.buildSessionFactory();
        Session ses = sf.openSession();

        ses.save(s);
        ses.beginTransaction().commit();
        ses.evict(s);

        ses.close();
        //                
        // ses = sf.openSession();

        // s = (Student)ses.get(Student.class, 1);
        // System.out.println("Name="+s.getName());
        //                System.out.println("Id="+s.getId());
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:Beans.NuevaRevision.java

public void revi() throws ClassNotFoundException {
    System.err.println("entro al nuevo");
    int cod_Revicion = Sequence.GetUltimoRegistro("select max(r.codigoRevision) from Revisiones r");
    int revision_proye = Sequence
            .GetUltimoRegistro("select max(r.codRevisionproyecto) from RevisionProyecto r ");

    System.out.println("codigo revicion : " + cod_Revicion);
    Session session = HibernateUtil.getSessionFactory().getCurrentSession();
    Transaction t = session.beginTransaction();
    try {//from w ww  . jav  a2 s.  co m
        String a = "";
        int codProyecto = 0;
        Revisiones re = new Revisiones();
        System.out.println("---");
        System.out.println("codigo " + cod_Revicion);
        re.setCodigoRevision(new BigDecimal(cod_Revicion));
        re.setDescripcion(nueva);
        Date fecha = new Date();
        re.setFecha(fecha);
        System.out.println("datos " + re.toString());
        session.save(re);
        t.commit();
        System.out.println("- 1");
        insertReviPro(re, revision_proye);
        FacesContext.getCurrentInstance().getExternalContext().redirect("PROVistaRevision-1.2.xhtml");
    } catch (Exception e) {
        System.err.println("Error revi" + e.toString());
    }

}

From source file:Beans.NuevaRevision.java

public void insertReviPro(Revisiones re, int revision_proye) throws ClassNotFoundException {

    Session session = HibernateUtil.getSessionFactory().getCurrentSession();
    Transaction t = session.beginTransaction();
    try {//  w  w  w.  j a  v a2  s . com
        System.out.println("entrooooo a insert 2");
        Proyectos pro = new Proyectos();
        pro = (Proyectos) FacesContext.getCurrentInstance().getExternalContext().getSessionMap()
                .get("Poryecto_Revi");//guardo un dato con nueva llave para recuperarla en la nueva vista
        System.out.println("Proyecto +++ : " + pro.getCodigoProyecto());
        RevisionProyecto rp = new RevisionProyecto();
        rp.setCodRevisionproyecto(new BigDecimal(revision_proye));
        rp.setProyectos(pro);
        rp.setRevisiones(re);
        session.save(rp);
        t.commit();
    } catch (Exception ex) {
        System.out.println("Error ReviPro  " + ex.toString());
    }

}

From source file:Beans.ObjetivosDocumento.java

public boolean insertObjetivos(Proyectos p) {
    boolean r = false;
    Session session = HibernateUtil.getSessionFactory().getCurrentSession();
    Transaction t = session.beginTransaction();
    try {//from   www  .j av  a 2 s  .c o  m
        int cod = 0;
        Objetivo temp = null;
        cod = Secuencia.seque("select max(cod_objetivo) from objetivos");
        for (int i = 0; i < obj.size(); i++) {
            temp = (Objetivo) obj.get(i);
            Objetivos ob = new Objetivos();
            System.out.println("Codigo " + cod);
            ob.setCodObjetivo(cod);
            ob.setDescripcion(temp.getObj());
            ob.setProyectos(p);
            session.save(ob);
            r = true;
            cod++;

        }
        t.commit();
    } catch (Exception ex) {
        r = false;
        System.out.println("Error - Objetivos " + ex.getMessage());
    }
    return r;
}

From source file:Beans.ObjetivosDocumento.java

public boolean insertProyect(Proyectos p) {
    boolean r = false;
    Session session = HibernateUtil.getSessionFactory().getCurrentSession();
    Transaction t = session.beginTransaction();
    System.out.println(".++++ " + p.getTipoProyecto());
    try {//from ww w .  j a v  a  2s  . co  m
        session.save(p);
        r = true;
        t.commit();
    } catch (Exception ex) {
        r = false;
        System.out.println("Error -Proyecto " + ex.getMessage());
    }
    return r;
}

From source file:beans.Register.java

public String registerNewMember() {
    if (member.getName() != null && !member.getName().isEmpty() && member.getEmail() != null
            && !member.getEmail().isEmpty()) {
        Session session = hibernate.HibernateUtil.getSessionFactory().openSession();
        session.beginTransaction();/*from  w  ww.j  a v  a2 s  . c o m*/
        session.save(member);
        session.getTransaction().commit();
        session.close();
        lend.fillMember();
        return "memberregister2lend";
    } else {
        error = "Fill the name and email fields!";
        return "";
    }
}

From source file:beans.Register.java

public String registerNewBook() {
    if (book.getAuthor() != null && !book.getAuthor().isEmpty() && book.getTitle() != null
            && !book.getTitle().isEmpty() && book.getPages() != 0) {
        Session session = hibernate.HibernateUtil.getSessionFactory().openSession();
        session.beginTransaction();//ww  w.  java  2  s .c  o m
        session.save(book);
        session.getTransaction().commit();
        session.close();
        return "bookregister2index";
    } else {
        error = "Fill the author, title and pages fields!";
        return "";
    }
}

From source file:bikerent.AddCustomer.java

public static void main(String[] args) {
    // Configure the session factory
    configureSessionFactory();//from w ww  .  j  ava  2s  .c  o  m

    NewCustomer custframe = new NewCustomer();
    custframe.addWindowListener(new WindowAdapter() {
        public void windowClosing(WindowEvent e) {
            if (custframe.getOK()) {

                System.out.println("Firstname: " + custframe.getFirstname());
                System.out.println("Lastname: " + custframe.getLastname());
                System.out.println("Dob: " + custframe.getDob());
                System.out.println("Mail: " + custframe.getMail());
                System.out.println("Password: " + custframe.getPW());

                Address addr = new Address(custframe.getStreet(), custframe.getHousenr(), custframe.getZip(),
                        custframe.getCity(), custframe.getCountry());
                this.saveCustomer_(custframe.getFirstname(), custframe.getLastname(), custframe.getDob(),
                        custframe.getMail(), custframe.getPW(), addr);
            }

        }

        public Boolean saveCustomer_(String fname, String lname, String DOB, String Mail, String PW,
                Address addr) {

            SimpleDateFormat format = new SimpleDateFormat("dd.MM.yyyy");
            java.util.Date date = null;
            try {
                date = format.parse(DOB);
            } catch (ParseException ex) {
                Logger.getLogger(AddCustomer.class.getName()).log(Level.SEVERE, null, ex);
            }
            java.sql.Date sqlDate = new java.sql.Date(date.getTime());
            Customer cust;
            cust = new Customer(fname, lname, sqlDate, Mail, PW, addr);

            Session session = null;
            Transaction tx = null;

            try {
                session = sessionFactory.openSession();
                tx = session.beginTransaction();
                // Saving to the database
                session.save(cust);
                // Committing the change in the database.
                session.flush();
                tx.commit();

                // Fetching saved data
                List<Customer> custList = session.createQuery("from Customer").list();

                System.out.println("customer:");
                for (Customer c : custList) {
                    System.out.println("Name: " + c.getName());
                }
                System.out.println("addresses:");
                // Fetching saved data
                List<Address> addrList = session.createQuery("from Address").list();

                for (Address a : addrList) {
                    System.out.println("Name: " + a.getStreet());
                }

            } catch (Exception ex) {
                ex.printStackTrace();

                // Rolling back the changes to make the data consistent in case of any failure 
                // in between multiple database write operations.
                tx.rollback();
            } finally {
                if (session != null) {
                    session.close();
                }
            }
            return true;
        }
    });
}

From source file:bikerent.AddDeleteEntity.java

private static void addCustomer(Session session) {

    // CUSTOMER 1 #########################

    Date d1 = generateDate("01.11.1990");

    Address a1 = new Address("Teststreet", "12", "22456", "Hamburg", "Germany");

    Customer c1 = new Customer("Sheldon", "Cooper", d1, // 01.11.1990
            "s.cooper@bla.de", "12345", a1);

    // CUSTOMER 2 #########################

    Date d2 = generateDate("05.02.1990");

    Address a2 = new Address("Blastreet", "4", "22489", "Hamburg", "Germany");

    Customer c2 = new Customer("Leonard", "Hofstadter", d2, // 05.02.1990
            "l.hofstadter@test.de", "12345", a2);

    // CUSTOMER 3 #########################

    Date d3 = generateDate("17.05.1984");

    Address a3 = new Address("abcstreet", "67", "55678", "Berlin", "Germany");

    Customer c3 = new Customer("Rajesh", "Koothrappali", d3, // 17.05.1984
            "r@koothrappali.de", "12346", a3);

    session.save(c1);
    session.save(c2);//from   w  w  w. j av  a  2  s .  com
    session.save(c3);
}

From source file:bikerent.AddDeleteEntity.java

private static void addBikes(Session session) {

    // FEMALE BIKE 1 ################
    Female f1 = new Female(10.0, "City", "Orton", "4570a45", Color.GREEN, 7, 52);

    // FEMALE BIKE 2 ################
    Female f2 = new Female(12.0, "City", "Vermont", "479bc45", Color.RED, 7, 54);

    // MALE BIKE 1 ##################
    Male m1 = new Male(15.0, "Mountainbike", "Merida", "82574a22", Color.BLUE, 14, 26);

    // CHILD BIKE 1 #################
    Child c1 = new Child(8.0, "Race", "Vermont", "20578if1", Color.GRAY, 3, 18, true);

    session.save(f1);
    session.save(f2);/*w w  w .j a v a2 s  .  co  m*/
    session.save(m1);
    session.save(c1);
}