JPA 实体和 DDD 实体应该是同一个类吗? [英] Should JPA entities and DDD entities be the same classes?

查看:33
本文介绍了JPA 实体和 DDD 实体应该是同一个类吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有些类根据 DDD 是实体,有些类具有 @javax.persistence.Entity 注释.它们应该是同一个类吗?或者 JPA 实体是否应该充当映射器的机制(https://martinfowler.com/eaaCatalog/dataMapper.html) 从数据库加载 DDD 实体(并存储它们)并保持在域模型之外?

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 should JPA entities act just as a mechanism for a mapper (https://martinfowler.com/eaaCatalog/dataMapper.html) to load DDD entities from a database (and store them) and be kept outside the domain model?

如果将数据库元数据分离并存储在外部(例如,在 XML 中)会有所不同吗?如果这些类是实体,边界在哪里?我认为从 XSD(例如,使用 JAXB)或什至使用 MyBatis Generator 从数据库生成的类不是 DDD 中理解的实体.

Would it make a difference if database metadata were separated and stored externally (for example, in XML)? If such classes are entities, where is the boundary? I think classes generated from XSD (for example, with JAXB) or even from database with MyBatis Generator are not entities as understood in DDD.

推荐答案

那真的是一个实现细节.它们可能是也可能不是,这取决于您的 ORM 的灵活性.例如,如果您的 ORM 允许映射您的域对象而不会因持久性问题而污染它们,那么这就是需要较少开销的方法,我会采用这种方法.

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.

另一方面,如果您的 ORM 不够灵活,那么您可以采用实用的混合方法,其中您的 AR 和它的状态是两个不同的类,并且状态类足够简单,可以轻松映射.请注意,AR 仍将负责保护其此处的状态,并且不会从 AR 外部直接访问状态对象.Vaughn Vernon 在此处.

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.

这篇关于JPA 实体和 DDD 实体应该是同一个类吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆