What is the best practice when to start a new session or transaction for batch jobs using spring / hibernate?

I have a set of batch / cron jobs in Java that call my service classes. I also use Hibernate and Spring.

Initially, the batch layer always created an external transaction, and then the batch job called the service to get a list of objects from the database with the same session, and then called the service to process each object separately. Theres is the tx tip set for my service level to roll back to any cast. So if an exception occurs on the 5th object, the first 4 objects that were processed are rolled back again, because they are all part of the same transaction.

So, I thought that this external transaction created in the batch layer was not needed. I deleted this and now I call the service to get a list of objects. Then call another service to process each object separately, and if one of these objects fails, the others will still be saved because it is a new transaction / session for each service call. But the problem that I have here now is to get a list of objects, when I pass each object to the service for processing, if I try to get one of the properties, I get a lazy initialization error, because the session used to load this object (from the list ) closes.

Some parameters that I was thinking about were just to get a list of identifiers in a batch job and pass each identifier to the service, and the service would retrieve the entire object in one session and process it. Another is to set lazy loading to false for these object attributes, but this will load everything every time, even if sometimes nested attributes are not needed.

I could always go back to how it was originally with an external transaction around each batch job, and then create another transaction in the batch job before each service call to process each individual object ...

What is the best practice for something like this?

+3
source share
1 answer

, , , OpenSessionInView. , . , AntiPattern .

, -, , , . , . - N + 1 , cron, . , , DAO, *.

, Open Session In View , . Spring , , . , , .

Edit

, , , Open Session , , - , .

, , "-" . . Spring , , . , , , read-write, . , , , @Transactional. @Transactional .

.

+2

All Articles