Should JPA entities and DDD entities be the same classes?

Your JPA entities should be the domain entities. Why? Your domain entities should express some strong constraints, e.g. by

  • Having parameterized constructors
  • Not exposing all setters
  • Do validation on write operations

If possible, a domain entity should always remain a valid business entity. By introducing some kind of mapper, you introduce a possibility to automagically write arbitrary stuff into your domain entities, which basically renders your constraints useless.

The other option would be enforcing the same constraints on JPA and domain entities which introduces redundancy.

Your best bet is keeping your JPA entities as ORM-agnostic as possible. Using Hibernate, this can be done using a configurating class or XML file. But I am no Java EE/JPA guy, so it's hard for me to give a good implementation advice.


That's an implementation detail really. They could be or they could not depending on the flexibility of your ORM. For instance, if your ORM allows to map your domain objects without polluting them with persistence concerns then that's the approach that requires the less overhead and which I'd go for.

On the other hand, if your ORM is not flexible enough then you could go for a pragmatic hybrid approach where your AR and it's state are two different classes and where the state class is simple enough to easily be mapped. Note that the AR would still be responsible to protect it's state here and the state object wouldn't be accessed directly from outside the AR. The approach is described by Vaughn Vernon here.