1

I am newbie to Hibernate framework and I am curious about the way persist and update work.

Currently in my project when I would like to persist or update collection of data into database, I am doing it one by one via looping method. For instance,

    public persistData(){
       List<Person> personList = new ArrayList<>();
       for(Person person : personList){
            session.persist(person);
       }
    }

Is it possible to, for example,

    session.persist(personList);

Or there is anyway else I can persist/update collection of data at once without looping?

Editted: I have found Hibernate Batch Processing in How to insert multiple rows into database using hibernate? and Best way to insert a good amount of records in hibernate

I am developing generic class for persist/update/delete data with hibernate, should I provide the method with

    public void (List<T> addedItemList)

or

    public void (T addedItem)

For my understanding, bulk persist should be done with large amount of transactions right? If some times there is only 1 or 2 objects to be persisted, is batch processing still appropriate?

Community
  • 1
  • 1
Gibi
  • 451
  • 1
  • 3
  • 12
  • 1
    You might start with reading the documentation: http://hibernate.org/orm/ (picking the version you use). – Uwe Allner Apr 25 '16 at 06:46
  • 1
    AFAIK there is no bulk update method. Wrap your `for` loop in a transaction and committing it at the end of the method will be efficient. If you've large number of rows use [batch inserting](https://docs.jboss.org/hibernate/orm/3.3/reference/en/html/batch.html#batch-inserts) – Bunti Apr 25 '16 at 06:51

1 Answers1

0

The main point here is to begin the transaction, persist all, and then commit. Try not using the @Transaction since you are doing it with the code.

                EntityManager em = entityManagerProvider.get();
//                em.clear();//remove this if caching is necessary
                em.getTransaction().begin();
                for(buildings b:buildingsArray) {
                     em.persist(b);
                }
                em.getTransaction().commit();
3xCh1_23
  • 1,491
  • 1
  • 20
  • 39