好的,假设我有一个“Person”实体,它需要将“Person”作为属性(比如, friend )
由于这是多对多连接,如果我使用 SQL 创建此模式(我不是,我使用 hbm.ddl.auto 为我做)我可能会创建另一个包含 2具有 2 个 id 的列(每个 friend 1 个)
但是,我不确定如何在 hibernate 中对此进行注释,我这样做了:
class PersonEntity {
.
.
@ElementCollection
private List<PersonEntity> friends ;
.
.
}
问题是,我不确定这是最好的方法..例如,我“在想”,每当我将 friend 添加到列表中并坚持下去时,它将作为表中的下一行插入,因为我可以'似乎没有索引这个字段我想象数据检索效率低下。
你能提出更好的方法来解决这个问题吗?
最佳答案
您正在寻找 @ManyToMany
和 @JoinTable
.
The api doc of ElementCollection说:
Defines a collection of instances of a basic type or embeddable class
您有一个实体实例的集合。见 http://docs.jboss.org/hibernate/stable/annotations/reference/en/html_single/#eentity-mapping-association-collection-manytomany了解如何使用这些注释。
关于hibernate - 将同一实体作为集合映射到自身,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7566847/