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 ?
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.
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.
The @Cascade annotation enables Hibernate to persist the collections associated with the main instance.
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();
Just iterate over it and persist it one by one
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With