Should JPA entities and DDD entities be the same classes?

后端 未结 3 1053
忘了有多久
忘了有多久 2020-12-31 13:30

There are classes that are entities according to DDD, and there are classes that have @javax.persistence.Entity annotation. Should they be the same classes? Or

3条回答
  •  佛祖请我去吃肉
    2020-12-31 14:22

    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.

提交回复
热议问题