Java – Separating Business logic from DB-logic with transactions

designdesign-patternsjavatransaction

architecture

We have three layers in our application. Service layer to provide an external API. BO layer for our business logic, and a DAO layer for our database connection.

Let's say every time we update a File, we also want to change something in the Folder, for example 'last modified date'.
This needs to be done in a transaction. Either it succeeds and both File and Folder are edited. Or there's a failure and the transaction gets rolled back so both objects are in the previous state.

The "Edit a folder when a file get edited"-action is purely business logic. So this would mean it belongs in the BO-layer.
However, we use Objectify for our Database, so to start a transaction we need to call ofy().transact(…).
If we call this function in the BO layer, this breaks our design as there will be Database specific calls (Objectify) in our Business layer.

What would be a clean solution for this problem?

Best Answer

How you cut your transactions is indeed business logic. So let your DAO layer provide a db framework independent API for the transact method you mentioned (and probably for things like commit and rollback). Then you can use it from your BO layer without making it dependent from your database or your db framework.