简体   繁体   English

JPA:建模m:n关系和联接表值

[英]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: 我有三个问题:

  1. Is this the right way to model the problem of additional fields in JPA 2.0? 这是在JPA 2.0中建模附加字段问题的正确方法吗?
  2. I not allowed to use both user and group in user_group as primary key since they are not valid primary key types. 我不允许同时使用user_group中的user和group作为主键,因为它们不是有效的主键类型。 Is it really necessary to declare a new primary. 确实有必要声明一个新的主数据库。
  3. Is this a common workflow with these join-tables/entities? 这是这些联接表/实体的通用工作流程吗?

... ...

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! 非常感谢!

  1. Yes, it's the good way to do it. 是的,这是很好的方法。
  2. It's possible to have a composite primary key consisting of two ManyToOne associations, but it's much more complex, both in the mapping and in the rest of the application, to handle that, and it's also less efficient. 可能有一个由两个ManyToOne关联组成的复合主键,但是在映射和应用程序其余部分中,它要处理起来要复杂得多,而且效率也较低。 You have an entity, so just do like for all the other entities and use an auto-generated, single-column primary key. 您有一个实体,因此就像对所有其他实体一样,并使用自动生成的单列主键。 The fact that this entity used to be a join table of a many-to-many association is irrelevant. 该实体曾经是多对多关联的联接表的事实是无关紧要的。
  3. Yes, that seems OK, except the 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. 我还将为实体本身使用另一个名称。 Something like "Membership" for example. 例如“会员资格”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM