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

查看:181
本文介绍了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天全站免登陆