为什么要使用Hibernate映射组件?
我正在学习 hibernate,并且遇到了 Hibernate 映射组件。 如果我们可以为学生和地址提供相同的 pojo 类,为什么我们要使用它呢?
I am learning hibernate an I came across Hibernate Mapping Component.
Why should we use it if we can have the same pojo class for student and address?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你可以。但这并不意味着你想要。
原因一:您希望以不同的方式对它们进行建模
在对象中,您希望以最佳方式对某些内容进行建模。这意味着一件事是学生和其他地址。将来,每个学生可能有更多地址,或者没有,因此如果您有两个不同的对象,迁移到该模型将会更容易。
将其视为高内聚和低耦合(良好的设计模式)。每个类别都有其意义、责任和有限的行动范围。班级越孤立,变化就越准时。您的代码也将更加模块化。
相比之下,在表中,您为了获得性能和更直接的查询而做出让步。这意味着您可以对模型进行非规范化(例如加入学生和地址)。
原因二:遗留模型
举例来说。如果您有一个旧的单个表并想要使用两个对象,则需要此映射。或者...如果您的应用程序已经基于两个对象创建,但您的数据库已重新设计,并且您认为一张表更好。
You can. But that doesn't mean you want.
Reason one: you want to model them differently
In objects you want to model something the best possible way. That means one thing are Students and other Addresses. In a future you could have more Address per student, or none, so migration to that model will be easier if you have two differents objects.
Think of it as high cohesion and low coupling (good design patterns). Each class has its meaning, its responsability, its limited range of action. The more isolated classes are, the more punctual changes will be. The more modular your code will be too.
By contrast, in tables you make concessions in order to gain performance and more direct queries. That means you can denormalize your model (like joining students and addresses).
Reason two: legacy models
By example. If you have a legacy single table and want to use two objects, you need this mapping. Or... if your application is already made, based on two objects, but your database is reengineered and you decide one table is better.
还有一点是,Address(此处被视为组件)不能有自己的主键,它使用封闭的 Student 实体的主键。
One more point is that Address (which is treated as component here) cannot have its own primary key, it uses the primary key of the enclosing Student entity.