Jeff
Jeff

Reputation: 1591

Java Persistence: Design with it in mind from the beginning or add in later?

I am doing things now like writing classes and their unit tests -- business logic. Without question, I will need to have something like JPA to allow me to store these classes and initialize the application from a database. I also know that I will need to do a lot of operations within a transaction.

My question is, does it make sense to implement the business logic first and then worry about persistence later or am I asking for trouble in this way -- perhaps instead I should be incorporating persistence in my design from the start: it might be very hard to add it in later? Or is there an approach where business logic can be totally ignorant of persistence? The reason I am guessing not is that the persistent classes need annotations.

Anyway, I could have been more succinct -- maybe the title says it all.

Cheers.

Upvotes: 1

Views: 177

Answers (1)

kostja
kostja

Reputation: 61538

Isolating the implementation from a particular technology is a best practice. In general, you should be better off developing an application without preparing to use JPA.

For this, you can use a separate domain model for your business logic. The domain objects should be mapped to/from a persisteable representation at the boundaries of your business logic layer.

Domain driven design, clean architecture, hexagonal architecture (and probably some others) are different but closely related approaches that emphasize the separation of business domain from frameworks.

The primary benefit is a clean separation of concerns. You can reach a very good testability for your code with very fast tests that do not rely on the DB. You also can switch persistence technologies (going with in-mem DBs or flat files if you should so desire) with much less pain.

The downside is that you will have to define a boundary mapping between your domain classes and persistent classes.

Having said that, sometimes fully embracing a framework can have it's own benefits that have to be weighed against clean design. When creating a simple, one-off webapp, it can make sense to use JPA entities all the way - even using attached JPA entites for display in the UI - this is called 'transaction view'.

The expected benefit is simplicity - sometimes there is no use in introducing a 'business logic' layer if there is no logic to speak of.

Upvotes: 3

Related Questions