How to persist an Array List of type Entity in JPA
Asked Answered
A

3

20

How to persist an Array List of type Entity in JPA ?

For example, there is an entity called "Table". I am creating an array list ArrayList<Table> table = new ArrayList<Table>(); Trying to persist it using entityManager.persist(table); and it did not work. Any solution for this ?

Arte answered 27/11, 2012 at 8:33 Comment(1)
V
8
 EntityManagerFactory emf = Persistence.createEntityManagerFactory("TDEMSPU");
        em = emf.createEntityManager();


            em.getTransaction().begin(); 

        List<Enquiry> tempEnqList = tempEnqList();
        for (Iterator<Enquiry> it = tempEnqList.iterator(); it.hasNext();) {
            Enquiry enquiry = it.next();

            em.persist(enquiry);
            em.flush();
            em.clear();
        }

         em.getTransaction().commit();
Volnay answered 22/2, 2014 at 5:45 Comment(0)
F
4

Just iterate over it and persist it one by one

Fadeless answered 27/11, 2012 at 8:37 Comment(5)
There are a large number of records I need to persist each time and it is taking too much time to persist each record. So, finding a way to persist whole list at a time.Arte
@Arte - there's actually no way around it - there are no bulk operations for persisting new entites. If you are persisting the entities in a transaction, the provider will generate an optimized SQL for all entities at the end of the transaction.Lippold
Enable batch writing, java-persistence-performance.blogspot.com/2011/06/…Aslant
This action can produce an exception for access recurrently to the DataBase.Elmiraelmo
@MariaMercedesWyssAlvarez I'm quit sure your exception is not because of this action. If an exception would trigger in a case like saving several items one after another would be a major bug in jpa implementation. what makes you think that your exception is cause by iterating and saving?Fadeless
F
4

Since Java 8 you can use forEach with a method reference:

List<SomeEntity> entities = ...;

entities.forEach(entityManager::persist);
Foodstuff answered 22/6, 2022 at 9:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.