开发者

Mapping same entity to itself as a collection

开发者 https://www.devze.com 2023-04-08 04:21 出处:网络
Ok, say i have a \"Person\" entity which needs to have \"Person\"s as property (say, friends) Since this is a many to many connection, If i\'d create this schema using SQL (Which i\'m not, i\'m using

Ok, say i have a "Person" entity which needs to have "Person"s as property (say, friends) Since this is a many to many connection, If i'd create this schema using SQL (Which i'm not, i'm using the hbm.ddl.auto to do it for me) i'd probably make another table containing 2 columns wi开发者_StackOverflow社区th 2 ids (1 for each friend) However, i'm not sure how to annotate this in hibernate, i did this:

class PersonEntity {

.
.

@ElementCollection
private List<PersonEntity> friends ;

.
.
}

Problem is, i'm not sure it's the best way.. for instance, i'm "thinking" that whenever i add a friend to the list and persist it will be inserted as the next row in the table, and since i can't seem to index this field i'm imagining the data retrieval will be inefficient. Can you suggest better ways to solve this problem?


You're looking for @ManyToMany and @JoinTable.

The api doc of ElementCollection says:

Defines a collection of instances of a basic type or embeddable class

You have a collection of entity instances. See http://docs.jboss.org/hibernate/stable/annotations/reference/en/html_single/#eentity-mapping-association-collection-manytomany for how to use those annotations.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号