When inserting in a loop, javax persistence. TransactionRequiredException
I have an application using spring, hibernate and JTA
We received a request that exceeded the expected data (10000 elements). The general request is 10-100 elements
When processing this request, we try to insert a record for each element in the DB and complete it in the for loop
Pseudo code:
processRecords( list){ for (Element element: list){ dao.findBy -- This takes around 100 ms -- some other checks and logic dao.add(element); -- This takes around 150 ms dao.flush(); } }
This block takes a lot of time to process the records, and then I get it*
*
I tried to flush out the for loop without help. I tried to study the batch insertion of hibernate, but it was a huge application with a lot of customization. I didn't think it was an option because it would affect the whole application. In addition, I tried to find out where the transaction duration was configured. The only place I could find was the JTA on Weblogic and set it to 480 seconds
Any indicators on how to address this situation would be appreciated
Edit: increasing the JTA timeout in Weblogic has temporarily solved this problem, but I set it to a very large value of 5000 seconds. Does it improve the performance because I just insert 8K records (I know batch processing is an option, but there are some limitations in this customized framework)
Solution
Use @ transactional to control transactions
>Make sure you do not use propagation_ Never start transactions automatically > by using requirements_ New calls the service method to start a new transaction for each item in the list (or a subset of items in the list)
In the second step, you may need to call another bean to actually pick up the transaction annotations, and don't remember whether this applies to methods on the same object