[英]JPA: Modelling m:n relationship & join-table values
having am:n real-world relationship between some entities, eg user <---> group Now I want to model this relationship and store additional information based on it, eg a field "quality". 在某些实体(例如,用户<--->组)之间具有真实关系,现在我想对此关系建模并基于该关系存储其他信息,例如字段“ quality”。
I heard that I would have to create a new join table user_group as follows: 我听说我将必须创建一个新的联接表user_group,如下所示:
id | user_ref | group_ref | quality
----------------------------------
1 1 1 0.5
2 1 2 1.3
... ... ... ...
The corresponding entity has two related entities (private members) user and group, annotated with the @ManyToOne -annotation. 对应的实体具有两个相关的实体(私有成员)用户和组,并用@ManyToOne注释。 On the other hand, both, my user and my group have a set of related user_group-entities, both private members and declared with the @OneToMany -annotation.
另一方面,我的用户和我的组都有一组相关的user_group-entities,它们都是私有成员,并使用@OneToMany -annotation声明。
I have three questions: 我有三个问题:
... ...
EntityManager em = ...
...
em.getTransaction().begin();
User u = new User("Pete");
Group g = new Group("Anonymous workaholics")
UserGroup ug = new UserGroup();
ug.addUser(u);
ug.addGroup(g);
em.persist(u); em.persist(g); em.persist(ug);
em.getTransaction().commit();
em.close()
Thanks a lot! 非常感谢!
addUser()
and addGroup()
methods should be named setUser()
and setGroup()
: there's only one user and one group for a given UserGroup
. addUser()
和addGroup()
方法应分别命名为setUser()
和setGroup()
:给定的UserGroup
只有一个用户和一个组。 I would also use another name for the entity itself.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.