Domain Driven Design: Entities, Value Objects, Aggregates and Roots with JPA (Part 2)
Detour: Why use JPA in this demo?
For the purposes of this demo, JPA is an officially supported part of the Java ecosystem and is a mature and well documented Java-to-relational mapping tool. Yes, it has quite a few quirks. If you fight it you will probably lose (your mind). If you learn how to do the basics and don’t deviate from that it can be a used as a rapid application tool to support an agile TDD build on Java against a relational database.
Why is JPA not universally loved? I would say that it is not because JPA isn’t a serious bit of technology that has had a huge amount of investment in it. It is because of the famous object to relational impedance mismatch. Scala programmers will say that the problem is actually that mutable OO is a concept with many traps and limited utility making persistence hard but that is an entire topic on it’s own.
A lot of developers think that working with an RDBMS isn’t at all agile. Yet you can have JPA create tables into an in-memory Java database for Unit testing as you write the code. That is pretty agile. This demo code does exactly that. It is then only a matter of packaging and deploying a different configuration pointing your application at a beefy industrial database server. I worked on a few projects that ran into very few differences in behaviour between an in-memory Java RDBMS and the commercial database server. Finding a few simple workarounds was well worth the agility.
Why can we expect that logic tested on a Java in-memory database will most often work on an industrial database server written in C? Because SQL and JPA are both very mature and google usually has the answer to any differences between products. The agility of fast test turnaround on new customer logic with full test coverage of database access is a guaranteed to save you days of time. In my experience the gains more the justifies the efforts of setting things up to unit test against an in-memory database.
Another reason to use basic JPA techniques in the demo code is to make a point: that the database and its mapping is an implementation detail that should be hidden. If there is any ugliness due to the use of JPA then this can, and should, be hidden from any code that uses our object model. The sample code does this by lumping each root entity into its own package with a minimal public API.
In the next post, we will discuss that the demo project is a rich domain library, that is front-end agnostic, and that should be hidden behind a business API if it is to be shared between projects or teams.