Hibernate JPA 注解 1 到 0..1 关系
我正在尝试设置 1to0..1(零或一)关系,但遇到了问题。
现在我的假设是使用@OneToMany,而不是@OneToOne。
基本上我希望我的“子”表保存“父”的外键(我非常宽松地使用子和父)。我从来不需要独立加载“children”
这是我想要实现的基本表结构
ITEM {
ID
RELATED_ITEM_ID
}
INVOICE {
ID
}
CATALOGUE {
ID
}
表示为 Java 类,如下所示
class Item {
...
}
class Invoice {
@OneToMany(fetch=FetchType.EAGER, orphanRemoval = true, cascade = { javax.persistence.CascadeType.ALL })
@Fetch(FetchMode.JOIN)
@JoinColumn(name="RELATED_ITEM_ID", nullable=false)
Set<Item> items;
}
class Catalogue {
@OneToMany(fetch=FetchType.EAGER, orphanRemoval = true, cascade = { javax.persistence.CascadeType.ALL })
@Fetch(FetchMode.JOIN)
@JoinColumn(name="RELATED_ITEM_ID", nullable=false)
Set<Item> items;
}
上面的代码,如果我只在 hibernate 中注册了 Invoice 或 Catalog,将创建我想要的表,并工作完美。但是,一旦我注册了发票和目录,休眠就会向我抛出错误
org.hibernate.MappingException: Duplicate property mapping of _itemsBackref found in package.name.Item
I am trying to setup a 1to0..1 (zero or one) relationship, but am running into issues.
Now my assumption is to use the @OneToMany, and not @OneToOne.
Basically I want my "child" table to hold the foreign key to the "parent" (I use child and parent very loosely). I never need to load "children" standalone
This is the basic table structure I want to achieve
ITEM {
ID
RELATED_ITEM_ID
}
INVOICE {
ID
}
CATALOGUE {
ID
}
Reprsented as Java classes like the following
class Item {
...
}
class Invoice {
@OneToMany(fetch=FetchType.EAGER, orphanRemoval = true, cascade = { javax.persistence.CascadeType.ALL })
@Fetch(FetchMode.JOIN)
@JoinColumn(name="RELATED_ITEM_ID", nullable=false)
Set<Item> items;
}
class Catalogue {
@OneToMany(fetch=FetchType.EAGER, orphanRemoval = true, cascade = { javax.persistence.CascadeType.ALL })
@Fetch(FetchMode.JOIN)
@JoinColumn(name="RELATED_ITEM_ID", nullable=false)
Set<Item> items;
}
The above code, if I only have Invoice or Catalogue registered in hibernate will create the tables as I want, and work perfectly. However, as soon as I have both Invoice and Catalogue registered, hibernate throws me the error
org.hibernate.MappingException: Duplicate property mapping of _itemsBackref found in package.name.Item
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我认为不可能使用 Hibernate 映射此架构(至少,只要
Customer
和Recepient
不扩展同一实体)。使用以下模式会更容易:
I don't think it's possible to map this schema with Hibernate (at least, as long as
Customer
andRecepient
don't extend the same entity).It would be much easier to use the following schema instead:
我最终以作弊的方式让它按照我想要的方式工作。理想情况下,我并不想要这样的层次结构,但我需要让它工作,而且我觉得这是围绕休眠工作的妥协。
表示为 Java 类,如下所示
I sort of ended up cheating to get this to work how I want. I dont ideally want a hierachy like that, but I need to get this working, and I feel this is a compromise with working around hibernate.
Reprsented as Java classes like the following