I'm using JPA with with Google App Engine. Let's say I have a very simple @Entity consisting of a Key and a String, nothing more. I now create 10000 of these entities, put them in a list and now want to store all of them.
If I try to use an EntityManager em and a for loop to go through the List of all my entities...
for(MyEntity entity : listOfAllEntities) {
em.persist(entity);
}
.. I will get an IllegalArgumentException:
java.lang.IllegalArgumentException: can't operate on multiple entity groups in a single transaction.
As far as I understand it, I need to close and reopen the EntityManager for each persist() call. Of course, this is very time consuming. I'm trying to have a task running once a day that reloads all the entities. According to GAE policy, the task has a timeout of 30 seconds.
So an alternative is to only save 500 entities at a time and run the task multiple times which I think is more complicated than it has to be.
Is this the only way of achieving what I'm trying to do or am I missing something here?
Solution: All the answers point in the same direction. I simply created a One-To-Many relationship by creating a "dummy parent" entity. I don't really need a parent in my case and it doesn't make much sense in the real world so to speak. But after setting this dummy entity as parent of each of the child entities, I can save them exactly as I did before without caring too much about transactions. Thanks to all.
Perhaps this is oversimplified, but you could just add the X number of entities as children of a parent entity and this would cause them to be in the same entity group. This would allow you to persist them all in one transaction. Basically, create an owned one-to-many relationship between the parent entity and the children which are the objects you are trying to persist.
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