简体   繁体   English

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

[英]On abstract classes in Java and Hibernate annotations

I am planing to create an application relying on DB using Hibernate. 我计划使用Hibernate创建一个依赖于DB的应用程序。 I will have some similar classes like teacher and student and so on. 我会有一些类似的课程,如老师和学生等。 In DB they will have some fields with similar names. 在DB中,它们将具有一些具有相似名称的字段。 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. 所以我想知道我是否可以为Name,SName等标准字段创建一个带有注释的类,以便在教师学生中扩展该类等等。 Will it work? 它会起作用吗? Does any one use it in such way? 有没有人以这种方式使用它?

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. 看看Peter Coad的书:Java Design,了解更多信息。

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. 此外,如果您决定使用继承,您确实需要考虑表实现:单个表(对于子类型attribs使用null cols)单独的表或单个表用于超类,单独的表用于子类。

Hibernate has extensive support for different scenarios involving inheritance and polymorphism. Hibernate对涉及继承和多态的不同场景提供了广泛的支持。 See the documentation 请参阅文档

http://docs.jboss.org/hibernate/stable/core/reference/en/html/inheritance.html 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. 它的难易程度取决于你如何构建表格。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM