Question

I'm not sure if something special exists for this use case - but it felt like a case where someone was likely to have made some sort of useful structure/technique/design-pattern.

My Situation

  • I have a set of SQL commands executed from middle tier (Java) to insert/update/delete data to any of a set of very large tables via joins from a related staging table.

  • I have more SQL commands which update various derived tables based on the staging table/actual table contents. Different tables will interact with different derived tables via different queries (as usual). These commands may have to be interleaved with the first set depending on the use case - so, I can't necessarily execute set 1 then set 2 all at once.

My Question

So, I need to build a chain of commands that get executed sequentially, and I need to trigger a rollback if any of them fail. I'd like to do this in the most clear, documented way possible.

Does anyone know a standard way of coding this? I'm sure anyone migrating from stored procedure code to middle tier code has done this before and I don't want to reinvent the wheel if there are good options out there.


Additional Information

One of my main concerns is making everything clear. To elaborate, I'll have a set of queries specifically designed to:

  • Truncate staging table A' and populate it with primary keys targeting deletion records
  • Delete from actual table A based on join with A'
  • Truncate staging table A' and populate it with full data for upserts
  • Update/Insert records from A' to A based on joins

The same logic will apply to tables B, C, D, etc. Unfortunately, it can be the case where just A and C need an extra step, like syncing deletes to a certain derived table, to be done after the deletions but before the upserts.

I'd obviously like to group all the logic for updating a table, and I'd like to group all the logic for updating a derived table as well, but at execution time they have to be intelligently interleaved and this sounds messy to me.

Was it helpful?

Solution

Don't write such a thing yourself. This is what JTA was born for.

You can use either JPA or Spring to do it.

Annotate the unit of work as transactional and let the database and JDBC handle it.

If you must do it yourself, follow the aspect-oriented approach and make it a decorative "before & after" implementation.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top