关于Java和Hibernate注解中的抽象类

发布于 2024-09-28 07:56:20 字数 158 浏览 6 评论 0原文

我计划使用 Hibernate 创建一个依赖于数据库的应用程序。我会有一些类似的课程,比如老师和学生等等。在数据库中,它们将有一些名称相似的字段。所以我想知道是否可以创建一个包含标准字段(如名称、SName 等)注释的 Human 类,以便在教师学生等中扩展该类。它会起作用吗?有人以这种方式使用它吗?

I am planing to create an application relying on DB using Hibernate. I will have some similar classes like teacher and student and so on. In DB they will have some fields with similar names. So I wonder If I can create a class Human with annotations for standard fields like Name, SName and so on so to just extend that class in teacher student and so on. Will it work? Does any one use it in such way?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

◇流星雨 2024-10-05 07:56:20

我认为老师和学生不是人类的子类,而是人类可以扮演的角色。如果你将它们作为子类,那么你实际上是在说老师永远不可能成为学生,反之亦然。
此外,如果一个人从学生变成老师(反之亦然),那么你就会失去该对象的任何关联和历史。
相反,请考虑角色。在此示例中考虑组合和委托而不是继承。
有关这方面的更多信息,请参阅 Peter Coad 的书:Java Design。

另外,如果您决定使用继承,您确实需要考虑表的实现:单表(子类型属性为空列)单独的表或超类的单表和子类的单独表。

I would suggest that teacher and student are not subclasses of human, but rather are roles that a human can play. If you make them subclasses then you are effectively saying that teacher can never be a student and vice versa.
Also, if one goes from being a student to teacher (or vice versa) then you lose any associations and history for that object.
Consider roles instead. Consider composition and delegation instead of inheritance in this example.
Take a look at Peter Coad's book: Java Design for more on this.

Also, you do want to think about the table implementation if you do decide to use inheritance: single table (with null cols for the subtype attribs) separate table or single table for super class and separate tables for subclasses.

调妓 2024-10-05 07:56:20

Hibernate 对涉及继承和多态性的不同场景提供了广泛的支持。请参阅文档

http://docs.jboss.org/ hibernate/stable/core/reference/en/html/inheritance.html

简短的答案是,是的,您可以完全按照您想要的方式进行操作 - 创建一个具有子类公共字段的基类。它的难度/涉及程度取决于您如何构建表格。

Hibernate has extensive support for different scenarios involving inheritance and polymorphism. See the documentation

http://docs.jboss.org/hibernate/stable/core/reference/en/html/inheritance.html

The short answer is, yes you can do exactly what you want -- create a base class with fields common to subclasses. How hard/involved it is depends on how you structure the tables.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文