Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
467 views
in Technique[技术] by (71.8m points)

jpa - Hibernate Best Practices: Avoiding Many-To-Many and 'exotic' relationships

The hibernate best practices states that many-to-many associations are rare and should be avoided.

Do not use exotic association mappings:

Practical test cases for real many-to-many associations are rare. Most of the time you need additional information stored in the "link table". In this case, it is much better to use two one-to-many associations to an intermediate link class. In fact, most associations are one-to-many and many-to-one. For this reason, you should proceed cautiously when using any other association style.

A basic and common case would be: user can be in more than one team and a team can have more than one member.

Is there an alternative to using @ManyToMany, other than creating an entity for the join table? In the case of team/member, there is no additional data in the join table, so having Team>TeamMembership>User is not so practical.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

There is nothing intrinsically wrong with using @ManyToMany but in practice, you rarely have the opportunity to use it. Usually you need additional attributes on the link itself, at which point, the relationship becomes an entity of its own.

One example from my experience was the kind of person/team relationship you described. I used a @ManyToMany at first, but had to turn it into a @OneToMany once I needed to add an effective-date on the relationship (person belongs to team at specific point in time).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...