如何对 @Any 带注释的属性进行双向映射?
在本文中 http://www.jroller.com/eyallupu/entry/hibernate_the_any_annotation也在这个问题中 如何使用 Hibernate @Any 相关注释?,解释了如何使用@Any注解。但我如何才能借阅每张 DVD/VHS/书籍呢?如何在 DVD/VHS/BOOK 上进行映射定义?
In this article http://www.jroller.com/eyallupu/entry/hibernate_the_any_annotation and also in this question How to use Hibernate @Any-related annotations?, how @Any annotation can be used was explained. But how can I get borrows for each DVD/VHS/BOOK? How can I do mapping definition on DVD/VHS/BOOK?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我不认为这是受支持的,并且如文档中所述:
虽然我知道引入此注释是为了将关联属性映射到没有共同祖先实体的不同类型的实体,但我认为最好为其他实体引入基本类型将继承自双向关系。
另请参阅
I don't think this is supported and, as mentioned in the documentation:
While I understand that this annotation has been introduced to map an association property to different types of entities that don't have a common ancestor entity, I think it would be better to introduce a base type the other entities would inherit from for bidirectional relations.
See also
是的,一侧是多态的(用 @Any 或 @ManyToAny 映射)的双向关联的问题是 Hibernate 自动生成无效的外键。就我个人而言,我认为这是一个错误,而不是使用错误。
您可以通过显式指定外键来解决这个问题,即不依赖 Hibernate 来推断它。在借用<--> DVD/VHS/Book 示例,假设您希望在“借用”和 DVD/VHS/Book(“项目”)之间建立双向、多对一的关联,然后将其映射到“借用” 一侧使用多态@Any 机制来item,并且在item 一侧使用@OneToMany 来借用。
但是:在后一个属性/获取器上,您还明确指定要使用的连接列,例如“ITEM_ID”。这应该强制Hibernate仅使用“ITEM_ID”,并且不(正如我所见)ITEM_ID + ITEM_TYPE,它默认从另一个上的@Any定义推断出来边。
如果您没有 DVD/VHS/Book 的“Item”超类,则必须在每个类中声明它,例如:
Yes, the problem with bi-directional associations where one side is polymorphic (mapped with @Any or @ManyToAny), is that Hibernate auto-generates an invalid foreign key. Personally, I view this as a bug, not a usage error.
You can get around this by specifying the foreign key explicitly, i.e. not rely on Hibernate to infer it. In the Borrow <--> DVD/VHS/Book example, let's say you want a bi-directional, many-to-one association between Borrow and DVD/VHS/Book (the "item"), then you map it on the Borrow side with the polymorphic @Any mechanism to item, and on the item side with a @OneToMany to Borrow.
BUT: on the latter property/getter, you also specify, explicitly, the join column to use, e.g. "ITEM_ID". That should force Hibernate to use only "ITEM_ID", and not (as I've seen) ITEM_ID + ITEM_TYPE that it infers by default from the @Any definition on the other side.
If you don't have a "Item" superclass for DVD/VHS/Book, you'll have to declare this in each class, something like: