使用 DDD 映射用户、地址、国家/地区
我正在尝试使用 spring、hibernate 并首次遵循 DDD 创建一个电子商务网站。
目前的情况是这样的。我正在将对象 USER 视为聚合根,它具有地址列表(以前的地址和当前地址),并且对于每个地址都有关联的国家/地区(isocode、名称)。
我假设地址和国家/地区是值对象。与用户严格相关。
在 @Entity 类 User 中,有:
@ElementCollection
@CollectionTable(name = "addresses", joinColumns = @JoinColumn(name = "address_id"))
@OrderColumn(name="user_id")
private List<Address> addresses;
在 @Embeddable 类 Address 中,我想为 Country 创建一个单独的表,我可以在初始化期间填充该表,并且 Address 只有一个外键。
我尝试了@Embeddable Country 和地址 @嵌入式 private Country 国家
以及@SecondaryTable ..但这只能在@Entity 类中使用..所以问题是Country 的字段保存在地址表中。
我应该为国家/地区创建一个@Entity 吗?或者还有另一种方法来映射这些类?
I'm trying to create an ecommerce website using spring, hibernate and for the first time following DDD.
At the moment the situation is this. I'm considering the object USER as aggregate root which has a list of addresses (previous ones.. and current) and for every address there is associated a Country (isocode, name)..
I assumed that Address and Country are Value Objects.. strictly related to the user.
In the @Entity class User there is:
@ElementCollection
@CollectionTable(name = "addresses", joinColumns = @JoinColumn(name = "address_id"))
@OrderColumn(name="user_id")
private List<Address> addresses;
In the @Embeddable class Address I would like to create a separate table for Country that I can populate during the initialization and the Address has only a foreign key.
I tried @Embeddable Country and in Address
@Embedded
private Country country
and also @SecondaryTable .. but this can be used only in @Entity class.. So the problem is that the fields of Country are saved inside the Address Table.
Should I create an @Entity for Country? Or there is another way to map these class?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我真的不明白将
Country
设为嵌入对象有什么意义。您将为所有用户一次又一次地重复相同的代码和名称,而不是仅仅让它们都指向相同的国家/地区。只需有一个包含所有国家/地区的表,由实体映射,并使所有引用的地址与国家/地区具有ManyToOne
关联。顺便说一句,如果你想设计一个必须输入地址的用户界面,我想你需要一个显示所有国家/地区可供选择的选择框:你不会每次都手动输入国家/地区的代码和名称。因此,您需要一个
Country
实体和一个findAll
方法来获取所有这些内容并填充您的选择框。I really don't see the point of making
Country
an embedded object. You'll repeat the same codes and names again and again for all your users, instead of just make them all point to the same countries. Just have a table with all the countries, mapped by an entity, and make all the addresses refer have aManyToOne
association with Country.BTW, if you want to design a UI where you have to enter an address, I guess that you'll need a select box displaying al the countries to choose from: you won't enter the code and name of the country manually each time. So you'll need a
Country
entity and afindAll
method to get them all and populate your select box.