0

I need to update my database before the Step starts and when it is complete. The purpose is to track in the database which processes are running at any one time. Before the step runs, it would insert a records; after the step completes, it will delete the record. Not elegant, but it's the requirement I have.

My idea was to implement this as a StepExecutionListener, issuing the insert and delete statements in the beforeStep and afterStep. This would also allow me to leverage the DataSource defined for the Job.

What if any are the drawbacks to this approach? Are there other hooks in the framework which would better solve this problem?

2 Answers2

1

Generally, what you describe should be possible. The only thing you have to be aware of is the transaction control, since the beforeStep and afterStep are outside the "normal" transaction handling. (here are 3 good posts, which explain the transaction handling in detail https://blog.codecentric.de/en/2012/03/transactions-in-spring-batch-part-1-the-basics/ , https://blog.codecentric.de/en/2012/03/transactions-in-spring-batch-part-2-restart-cursor-based-reading-and-listeners/ , https://blog.codecentric.de/en/2012/03/transactions-in-spring-batch-part-3-skip-and-retry/ )

You could also use separate steps (implemented as a simple Tasklet-Step) instead of using the before-/afterStep listener. Step1 inserts an an entry in the db or throws an exception, which causes the batch to fail or simply ends it (depending on your flow definition), step2 does your normal logic, step 3 removes the entry you inserted in step 1.

What I don't understand is, why do you have to actually write an entry into the db in order to check if it is available. Wouldn't a simple select be enough to that?

If I had to do it, I would implement you requirements with 2 steps, the first one checking the availability by executing a simple select, the second step executing the normal logic.

Hansjoerg Wingeier
  • 4,274
  • 4
  • 17
  • 25
  • Thanks for you input. Inserting a record during the beforeStep is about state management, not verifying if the database was available. – Brian Surratt Jan 05 '18 at 02:22
0

You are correct, You need implement StepExecutionListener. I think there are no drawbacks in this approach. Or you can add two different tasklet one for insert and one for delete

Niraj Sonawane
  • 10,225
  • 10
  • 75
  • 104