英文:
What's the best way to model Friendship using Java Hibernate and JPA
问题
让我们假设我有一个"Person"实体。
而且,一个"Person"可以与一个或多个其他"Persons"建立'Friendship'关系。
我会这样建模,例如,在一个表中有一个条目:
| Person Id 1 | Person Id 2 |
但是,从语义上讲,如果Person 1与Person 2是朋友,那么这与Person 2与Person 1是朋友是相同的。
| Person Id 1 | Person Id 2 |
当然,在Java中有很多方法,以及在查询中,比如((person1=x AND person2=y) OR (person1=y AND person2=x))
,我会确保这种等价关系得到尊重。但在数据库本身以及随后的存储库、JPQL查询等方面,有没有更有效的建模方式呢?
总结一下;我想要能够检查Person 1是否与Person 2是朋友,而不必进行两次检查 - (Person 1是否与Person 2是朋友) 或 (Person 2是否与Person 1是朋友)。习惯上,我只想说(是Person 1和Person 2是朋友)。
我希望能够隐含地建模这种等价关系,即如果A是B的朋友,那么B也自动成为A的朋友。
英文:
Let's say I have a Person entity.
And a Person can have a 'Friendship' relationship with one or more other Persons.
I would model that with, say, an entry in a table
| Person Id 1 | Person Id 2 |
But, semantically, if Person 1 is friends with Person 2
| Person Id 1 | Person Id 2 |
it is the same as saying Person 2 is friends with Person 1
| Person Id 2 | Person Id 1 |
Of course, there are lots of ways in Java, and in the query, such as ((person1=x AND person2=y) OR (person1=y AND person2=x))
that I would make sure that this equivalence is honoured. But what's a more efficient way to model this in the database itself, and in subsequent Repository, JPQL Queries etc.
To summarise; I want to be able to check whether Person 1 is friends with Person 2, without having two checks - (is Person 1 friends with Person 2) or (is Person 2 friends with Person 1). Idiomatically, I just want to say (are Person 1 and Person 2 friends).
I want to implicitly model the equivalence that is A is friends with B then B is automatically friends with A.
答案1
得分: 1
以下是翻译好的部分:
- 以下是人员实体类
@Entity
public class Person {
//Id and properties
@ManyToMany
@JoinTable(name="friendship",
joinColumns={@JoinColumn(name="person_id")},
inverseJoinColumns={@JoinColumn(name="friend_id")})
private Set<Person> friends = new HashSet<Person>();
// Getter and Setter methods
}
- 它将生成一个
person
表和一个friendship
表。person
表将仅包含与Person
相关的信息,而friendship
表将仅包含两列person_id
和friend_id
以保持关系。
英文:
- The following person entity class
@Entity
public class Person {
//Id and properties
@ManyToMany
@JoinTable(name="friendship",
joinColumns={@JoinColumn(name="person_id")},
inverseJoinColumns={@JoinColumn(name="friend_id")})
private Set<Person> friends = new HashSet<Person>();
// Getter and Setter methods
}
- It will generate a
person
table and afriendship
table.person
table will only contain information related toPerson
andfriendship
table will only have two columnsperson_id
andfriend_id
to keep the relationship.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论