Persistence: Automating Create transaction on connected Entities

I have an Entity Restaurant having a collection of Areas. For each Area, users have to manually insert a daily Annotation (more than one per-day is forbidden via unique constraint).

My goal is to automate the process

I created a Bean and connected it to a Scheduled Task. The Task workflow should be:

  • List the Restaurants having "automation" flag
  • List the Areas of each Restaurant
  • Find Areas with no Annotations yet
  • Insert missing Annotation

Supposing I must use EntityManager, my questions is: Where should I create the Transaction considering that:

  • I don't care if sombody is switching off the automation flag of a Restaurant while the Task is firing
  • If somebody deletes an Area in the while, the Annotation can be ignored
  • If somebody makes an insertion in the while the unique constraint will make the transaction roll-back
  • I don't want a single rolled back insertion to ruin the whole process

Thanks Lucio

Hi Lucio,

I would fisrt load a list of restaurants and save it in a list. Then, while iterating through the list, create and commit a new transaction for processing each restaurant.

Thank you Konstantin,

Indeed I created a list of Restaurants and Areas for each Restaurant via DataManager queries.
For each Area I query the DB to find Annotations for the day (with DataManager again). Then, only if an Area doesn’t have an Annotation I use EntityManager to insert it.

Your approach is definitely more correct, but the query is going to be a complicated one and I’m no sql expert…

Do you think my approach will lead to any pitfall?

I don’t think there can be a difference in complexity of queries between using DataManager and EntityManager. The only difference that can matter for you is that using EntityManager you can include multiple read and write operations in one transaction. While DataManager always loads and saves entities in separate transactions. BTW, you can persist new entities using DataManager as well - just pass them to commit().

1 Like

Thank you for the clarification Konstantin