将注释应用于从 @MappedSuperclass 继承的字段
具有:
@MappedSuperclass
class Superclass {
@Id
@Column(name = "id")
protected long id;
@Column(name="field")
private long field;
}
以及
@Entity
class Subclass extends Superclass {
}
如何在子类中使用 @GenerateValue 注释继承的 id 和使用 @Index 的字段?
Has:
@MappedSuperclass
class Superclass {
@Id
@Column(name = "id")
protected long id;
@Column(name="field")
private long field;
}
and
@Entity
class Subclass extends Superclass {
}
How to annotate inherited id with @GeneratedValue and field with @Index within Subclass?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
AFAIK,你不能。您可以做的是使用
AttributeOverride
和AssociationOverride
注释覆盖属性和关联(即更改列或连接列)。但你不能完全按照你的要求去做。对于
GenerateValue
,如果您不想在映射的超类中声明它,请考虑使用 XML 映射来覆盖该策略。对于
Index
(顺便说一句,这不是标准注释),您实际上是否尝试使用 Hibernate 的Table
注释在表级别声明它(我假设你正在使用休眠)?参考
AFAIK, you can't. What you can do is overriding attributes and associations (i.e. change the column or join column) using the
AttributeOverride
andAssociationOverride
annotations. But you can't do exactly what you're asking.For the
GeneratedValue
, consider using XML mapping to override the strategy if you don't want to declare it in the mapped superclass.For the
Index
(which is not a standard annotation by the way), did you actually try to declare it at the table level using Hibernate'sTable
annotation instead (I'm assuming you're using Hibernate)?References
至于
@GenerateValue
,可以这样做:As for
@GeneratedValue
, it is possible to do like this:如果您将注释应用到访问器方法,您也许能够做到这一点。 (我还没有尝试过,所以我不能保证它会起作用。)
。
You might be able to do this if you apply the annotations to the accessor methods instead. (I haven't tried this, so I can't guarantee that it'll work.)
.
以防万一其他人搜索此内容,我使用了以下代码,这会增加一些开销,但仅处理字段注释不应添加那么多:
返回的列表将包含所有带有
的父类和子类的所有字段mElement
是您要从中搜索注释的对象。希望这有帮助。Just in case anyone else searches for this, I used the following code which adds in some overhead, but for processing Field annotations only shouldn't add that much:
The returned list would contain all fields for all parent and child classes with
mElement
being the object you are searching for annotations from. Hope this helps.