DDD – entity vs package-by-feature

Let’s say, we have 3 Aggregates:

  • Order (“orders” package)
  • Customer (“customers” package)
  • Product (“products” package)

What I want to do now is to connect all of these aggregates on “Entity” level using JPA/Hibernate. But here comes another problem with entities accessibility (they must be public). What should I do in similar cases?

Answer

You have at least 3 options.

Let the persistence information spread into the domain entities, hence you have a total overlap between the persistence entities and the domain entities. That means, also, that you have to adapt, when there’s no simple way to handle it, the domain to the persistence constraints. For example, the way you manage the relationship one to many. And, as you note, you also need to make them public.

Another option is to extend the domain entities with classes that have the persistence information. It’s doable (I’ve done it one time) but it’s a mess when the domain grows up in unexpected ways.

Another option is to split the domain and the persistence entities. So you have the first ones that exist inside a package, that should go under the infrastructure layer, while the others stay in another package, unser the domain layer. In this way you can hide all the domain functions kwnd everything else) and publish only the things required to build an entity (a builder, for example). On the other side, all the persistence details stay outside the domain. But, you need a way to translate the domain entities into persistence ones and the opposite. It’s extra work but the good thing is that you can test every single thing and once it works, it works always.

Finally, in the real world you need to relax some aspects to adapt the domain to your infrastructure requirements/constraints.