Example usage for org.hibernate Session persist

List of usage examples for org.hibernate Session persist

Introduction

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

Prototype

void persist(Object object);

Source Link

Document

Make a transient instance persistent.

Usage

From source file:eu.trentorise.opendata.ckanalyze.managers.PersistencyManager.java

License:Open Source License

public static void insertInOneCommit(List<Object> os) {
    Session ss = PersistencyManager.getSessionFactory().openSession();
    ss.beginTransaction();//from ww w . ja v  a  2 s. c o  m
    for (Object object : os) {
        ss.persist(object);
    }
    ss.getTransaction().commit();
    ss.close();
}

From source file:exercise05_1.App.java

public static void main(String[] args) {
    // Hibernate placeholders
    Session session = null;
    Transaction tx = null;//  w  w  w  .  j av  a 2  s.co  m
    try {
        session = sessionFactory.openSession();
        tx = session.beginTransaction();

        //List<Order> orders=new ArrayList();
        Customer customer1 = new Customer("Masudur", "Rahman");
        Customer customer2 = new Customer("Fahim", "Muntasir");

        Order order1 = new Order(new Date("1/2/2015"));
        Order order2 = new Order(new Date("2/2/2015"));
        Order order3 = new Order(new Date("3/2/2015"));
        Order order4 = new Order(new Date("4/2/2015"));

        OrderLine orderline1 = new OrderLine(11);
        OrderLine orderline2 = new OrderLine(12);
        OrderLine orderline3 = new OrderLine(13);
        OrderLine orderline4 = new OrderLine(14);
        OrderLine orderline5 = new OrderLine(15);

        Product product1 = new Product("Laptop", "HP 430") {
        };
        Product product2 = new Product("Pen", "Fountain Pen") {
        };
        Product product3 = new Product("Chair", "delux Chair") {
        };
        Product product4 = new Product("Book", "Spring MVC") {
        };

        Product cd1 = new CD("Andrew Kishor", "Singerr");
        Product dvd1 = new DVD("Horror DVD");

        //Product  book1=new Book("Science Fiction Book");
        Product cd2 = new CD("Kumar Shanu", "Singer2");
        Product dvd2 = new DVD("Sci-Fie DVD");
        Product book2 = new Book("Literature book");

        //        orderline1.setProduct(product1);
        //        orderline2.setProduct(product1);
        //        orderline3.setProduct(product2);
        //        orderline4.setProduct(product4);
        //        orderline5.setProduct(product3);
        orderline1.setProduct(cd1);
        orderline2.setProduct(cd1);
        orderline3.setProduct(dvd1);
        orderline4.setProduct(book2);
        //orderline5.setProduct(dvd2);
        orderline5.setProduct(cd2);

        order1.addOrderLine(orderline1);
        order1.addOrderLine(orderline2);

        order2.addOrderLine(orderline3);
        order3.addOrderLine(orderline4);
        order4.addOrderLine(orderline5);

        customer1.addOrders(order1);
        customer1.addOrders(order3);

        customer2.addOrders(order2);
        customer2.addOrders(order4);

        session.persist(customer1);
        session.persist(customer2);
        tx.commit();
    } catch (HibernateException e) {
        if (tx != null) {
            System.err.println("Rolling back: " + e.getMessage());
            tx.rollback();
        }
    } finally {
        if (session != null) {
            session.close();
        }
    }
}

From source file:fi.uta.infim.usaproxylogdb.Main.java

License:Open Source License

/**
 * @param args/*from w  w w .  j  a v a2 s  .  c o  m*/
 * @throws Throwable 
 */
@SuppressWarnings({ "deprecation" })
public static void main(String[] args) {

    printLicense();

    UsaProxyLog loki;

    try {
        System.out.print("Parsing log file... ");
        loki = new UsaProxyLogParser().parseLog(args[0]);
        System.out.println("done.");
    } catch (ArrayIndexOutOfBoundsException ae) {
        printError(ae, "Please provide a file name.", true, true);
        return;
    } catch (Exception e) {
        printError(e, "Unable to parse log file.", true, true);
        return;
    }

    SessionFactory sf;

    try {
        System.out.print("Establishing database connection... ");
        Configuration cfg = new Configuration().configure(new File("hibernate.cfg.xml"))
                .addURL(UsaProxyLog.class.getResource("/META-INF/orm.xml"));
        sf = cfg.buildSessionFactory();
        System.out.println("done.");
    } catch (Exception e) {
        printError(e, "Unable to configure database connectivity. Check your configuration.", true, true);
        return;
    }

    try {
        System.out.print("Persisting log contents... ");
        Session s = sf.openSession();
        Transaction tx = s.beginTransaction();
        s.persist(loki);
        tx.commit();
        s.close();
        sf.close();
        System.out.println("done.");
    } catch (Exception e) {
        printError(e, "Unable to persist data.", true, true);
        return;
    }
}

From source file:fr.keyconsulting.oliphant.test.Benchmark.java

License:Open Source License

public void update(long id, boolean magic, boolean stale) throws SQLException {
    SessionFactory factory = magic ? magicSessionFactory : sessionFactory;

    Session session = factory.getCurrentSession();

    System.out.println("Hibernate: starting transaction");
    Transaction tx = session.beginTransaction();
    PersistentVersionedObject o1 = (PersistentVersionedObject) session.load(PersistentVersionedObject.class,
            id + 1);/*from www .  jav  a 2 s .co  m*/
    System.out.println("Hibernate: loading object " + id);
    PersistentVersionedObject o = (PersistentVersionedObject) session.load(PersistentVersionedObject.class, id);
    o.setChampString("valeur 2");

    if (stale) {
        Statement st = conn.createStatement();
        System.out.println("Updating object " + id + " outside Hibernate");
        st.executeUpdate("UPDATE persistentversionedobject SET version=version+1 WHERE id=" + id);
        st.close();
    }

    try {
        session.persist(o);
        tx.commit();
    } catch (Exception e) {
        System.out.println(e);
        System.out.println("  in " + e.getStackTrace()[0]);
    }
}

From source file:fr.keyconsulting.oliphant.test.unitTests.java

License:Open Source License

public void update(Class theClass, boolean magic, boolean stale, boolean cached) {
    long id = 0;//from www .j  a v  a 2s.c o  m
    SessionFactory factory = magic ? magicSessionFactory : sessionFactory;

    Session session = factory.getCurrentSession();

    System.out.println("Hibernate: starting transaction");
    Transaction tx = session.beginTransaction();

    if (cached) {
        System.out.println("Hibernate: pre-loading object " + id);
        Object o = theClass.cast(session.load(theClass, id));
    } else {
        factory.evict(theClass);
    }
    System.out.println("Hibernate: loading " + theClass + " " + id);
    PersistentVersionedObject o = (PersistentVersionedObject) session.load(theClass, id);
    o.setChampString("" + System.currentTimeMillis());

    if (stale) {
        try {
            System.out.println("Updating " + theClass + " " + id + " outside Hibernate");
            Statement st = conn.createStatement();
            String entityName = session.getEntityName(o);
            PersistentClass c = config.getClassMapping(entityName);
            st.executeUpdate("UPDATE " + c.getTable().getName() + " SET version=version+1 WHERE id=" + id);
            st.close();
        } catch (SQLException e) {
            fail();
            System.out.println(e);
            System.out.println("  in " + e.getStackTrace()[0]);
        }
    }
    try {
        session.persist(o);
    } catch (StaleObjectStateException e) {
        assertTrue(magic && stale);
        return;
    }
    assertFalse(stale && magic); // We should have had an exception
    try {
        tx.commit();
    } catch (StaleObjectStateException e) {
        assertTrue(stale);
        return;
    }
    assertFalse(stale); // We should have had an exception
}

From source file:fr.utbm.core.dao.AlertDao.java

public void registerAlert(Alert a) {
    Session session = HibernateUtil.getSessionFactory().openSession();
    try {//from  www .j a  v  a  2s  .  c o m
        session.beginTransaction();
        session.persist(a);
        session.getTransaction().commit();
    } catch (HibernateException he) {
        he.printStackTrace();
        if (session.getTransaction() != null) {
            try {
                session.getTransaction().rollback();
            } catch (HibernateException he2) {
                he2.printStackTrace();
            }
        }
    } finally {
        if (session != null) {
            session.close();
        }
    }
}

From source file:fr.utbm.gestion_de_formations_en_ligne.repository.HibernateClientDAO.java

public void insertClientHibernate(Client client) {
    Session session = HibernateUtil.getSessionFactory().openSession();
    session.beginTransaction();//from  w w  w.j a  v  a  2 s. c  om
    session.persist(client);
    session.getTransaction().commit();
}

From source file:fr.utbm.projetlo54.repository.HibernateCourseDAO.java

/**
 * Adds a course to the database and returns its code.
 * //ww w. j  a  v  a  2s. c  o  m
 * @param c the new course to add to the database
 */
public void addCourse(Course c) {
    Session session;
    session = HibernateUtil.getSessionFactory().openSession();
    try {
        session.beginTransaction();
        session.persist(c);
        session.getTransaction().commit();
    } catch (HibernateException e) {
        e.printStackTrace();
        if (session.getTransaction() != null) {
            try {
                session.getTransaction().rollback();
            } catch (HibernateException e2) {
                e2.printStackTrace();
            }
        }
    } finally {
        if (session != null) {
            try {
                session.close();
            } catch (Exception e) {
                System.out.println(e);
            }
        }
    }
}

From source file:generateday4hibernate.GenerateDay4Hibernate.java

/**
 * @param args the command line arguments
 *///ww w . j a  v a  2s.  c om
public static void main(String[] args) {
    // TODO code application logic here

    SessionFactory sessionFactory = new Configuration().configure("/resources/hibernate.cfg.xml")
            .buildSessionFactory();
    Session session = sessionFactory.openSession();
    Buyer br = new Buyer();
    Seller sl = new Seller();
    User user = new User();
    Product proud = new Product();
    //Product proud1=new Product();
    Category cate = new Category();
    BuyerBidProduct BuyerbidProduct = new BuyerBidProduct();
    BuyerBuyProduct BuyerbuyProuduct = new BuyerBuyProduct();

    user.setUserName("anotation");
    user.setFullName("azza hamdy");
    user.setDateOfBirth(new Date());
    user.setAddress("suez");
    user.setPhone("123456789");
    user.setEmail("azza@mail.com");
    user.setRegistrationDate(new Date());
    user.setPassword("4815162342");
    user.setMobile("01025012646");

    br.setUser(user);
    br.setValue("Tea");

    sl.setUser(user);
    sl.setValue("teaaa");

    proud.setName("product1");
    proud.setQuantity(5);
    proud.setExpirationDate(new Date());
    proud.setDescription("firstproduct insert");
    proud.setFinishDate(new Date());
    proud.setManufacturingName("Hibernare");
    proud.setOfferedDate(new Date());
    proud.setManufacturingDate(new Date());
    proud.setSeller(sl);

    Product proud2 = new Product();

    proud2.setName("product3");
    proud2.setQuantity(5);
    proud2.setExpirationDate(new Date());
    proud2.setDescription("firstproduct insert");
    proud2.setFinishDate(new Date());
    proud2.setManufacturingName("Hibernare");
    proud2.setOfferedDate(new Date());
    proud2.setManufacturingDate(new Date());
    proud2.setSeller(sl);

    cate.setValue("cate2");
    cate.setDescription("blala");
    cate.getProducts().add(proud2);

    BuyerbidProduct.setBuyer(br);
    BuyerbidProduct.setProduct(proud2);
    BuyerbidProduct.setDate(new Date());
    BuyerbidProduct.setAmount(4f);
    BuyerbidProduct.setQuantity(2);

    BuyerbuyProuduct.setBuyer(br);
    BuyerbuyProuduct.setProduct(proud);
    BuyerbuyProuduct.setPaymentDate(new Date());
    BuyerbuyProuduct.setQuantity(4);
    BuyerbuyProuduct.setAmount(3f);

    session.save(user);
    session.save(sl);
    session.save(br);
    session.save(proud);
    //            session.save(proud1);
    session.save(proud2);

    session.save(cate);

    BuyerbidProduct.setId(new BuyerBidProductId(br.getId(), proud2.getId()));
    session.save(BuyerbidProduct);
    BuyerbuyProuduct.setId(new BuyerBuyProductId(br.getId(), proud.getId()));
    session.save(BuyerbuyProuduct);

    session.beginTransaction();

    //session.persist(br);
    //session.persist(sl);

    session.persist(BuyerbidProduct);
    session.persist(BuyerbuyProuduct);

    session.getTransaction().commit();
    session.close();
    System.out.println("Insertion Done");
}

From source file:generatehibernate.GenerateHibernate.java

/**
 * @param args the command line arguments
 *//*from  w w w  . j av a  2s  . co m*/
public static void main(String[] args) {
    // TODO code application logic here
    Configuration cfg = new Configuration().configure("/resources/hibernate.cfg.xml");
    cfg.setInterceptor(new UserInterceptor());
    SessionFactory sessionFactory = cfg.buildSessionFactory();
    Session session = sessionFactory.openSession();

    Buyer br = new Buyer();
    Seller sl = new Seller();
    User user = new User();
    Product proud = new Product();
    //Product proud1=new Product();
    Category cate = new Category();
    BuyerBidProduct BuyerbidProduct = new BuyerBidProduct();
    BuyerBuyProduct BuyerbuyProuduct = new BuyerBuyProduct();

    user.setUserName("azza");
    user.setFullName("azza hamdy");
    user.setDateOfBirth(new Date());
    user.setAddress("suez");
    user.setPhone("123456789");
    user.setEmail("azza@mail.com");
    user.setRegistrationDate(new Date());
    user.setPassword("4815162342");
    user.setMobile("01025012646");

    br.setUser(user);
    br.setValue("Tea");

    sl.setUser(user);
    sl.setValue("teaaa");

    proud.setName("product1");
    proud.setQuantity(5);
    proud.setExpirationDate(new Date());
    proud.setDescription("firstproduct insert");
    proud.setFinishDate(new Date());
    proud.setManufacturingName("Hibernare");
    proud.setOfferedDate(new Date());
    proud.setManufacturingDate(new Date());
    proud.setSeller(sl);

    Product proud2 = new Product();

    proud2.setName("product4");
    proud2.setQuantity(5);
    proud2.setExpirationDate(new Date());
    proud2.setDescription("firstproduct insert");
    proud2.setFinishDate(new Date());
    proud2.setManufacturingName("Hibernare");
    proud2.setOfferedDate(new Date());
    proud2.setManufacturingDate(new Date());
    proud2.setSeller(sl);

    cate.setValue("cate2");
    cate.setDescription("blala");
    cate.getProducts().add(proud2);

    BuyerbidProduct.setBuyer(br);
    BuyerbidProduct.setProduct(proud2);
    BuyerbidProduct.setDate(new Date());
    BuyerbidProduct.setAmount(4f);
    BuyerbidProduct.setQuantity(2);

    BuyerbuyProuduct.setBuyer(br);
    BuyerbuyProuduct.setProduct(proud);
    BuyerbuyProuduct.setPaymentDate(new Date());
    BuyerbuyProuduct.setQuantity(4);
    BuyerbuyProuduct.setAmount(3f);

    session.save(user);
    session.save(sl);
    session.save(br);
    session.save(proud);
    //            session.save(proud1);
    session.save(proud2);

    session.save(cate);

    BuyerbidProduct.setId(new BuyerBidProductId(br.getId(), proud2.getId()));
    session.save(BuyerbidProduct);
    BuyerbuyProuduct.setId(new BuyerBuyProductId(br.getId(), proud.getId()));
    session.save(BuyerbuyProuduct);

    session.beginTransaction();

    //session.persist(br);
    //session.persist(sl);

    session.persist(BuyerbidProduct);
    session.persist(BuyerbuyProuduct);

    session.getTransaction().commit();
    session.close();
    System.out.println("Insertion Done");
}