Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to persist an Array List of type Entity in JPA

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 ?

like image 577
user1855852 Avatar asked Nov 27 '12 08:11

user1855852


People also ask

How do I persist a list in JPA?

Solution: Since JPA 2.0, you can use an element collection to persist a Collection of value types. You just need to annotate the attribute with @ElementCollection and the persistence provider will persist the elements of the Collection in an additional database table.

How do you save a list of entities in Spring data JPA?

For SpringData Jpa, a cleaner approach will be to use repository. saveAll instead of a for loop with repository. save . saveAll will automatically iterate through the list and save it.

Which annotation is used to persist a collection of value types?

The @Cascade annotation enables Hibernate to persist the collections associated with the main instance.


2 Answers

 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();
like image 179
Ravinath Avatar answered Oct 25 '22 09:10

Ravinath


Just iterate over it and persist it one by one

like image 32
Liviu Stirb Avatar answered Oct 25 '22 10:10

Liviu Stirb