Search code examples
hibernatejpaspring-bootentitymanager

Can you persist many entities of a variety of classes using a single javax.persistence.EntityManager?


Let's say you have table table1 and table table2.

I am using Springboot with hibernate JPA.

I declare the EntityManager object as below using @Persistencecontext annotation

 @PersistenceContext
 private EntityManager em;

And then I want to loop over a list of objects - some of these objects will be inserted in table1 and some in table2 - depending on the value of one of the object's attribute.

Table1 and Table2 are entity classes for table1 and table2 respectively. Both have the same schema.

Can you do the following?

 for(Object object: objectList){
     em.persist(new Table1(object.attribute1, object.attribute2));
     em.persist(new Table2(object.attribute1, object.attribute2));
    }

Solution

  • Yes, you can persist many entities of different class using single EntityManager