简体   繁体   English

玩2框架多对多关系更好的设计

[英]Play 2 framework many-to-many relation better design

In my app I have different User s and Item s, so each user can pick many items. 在我的应用程序中,我有不同的UserItem ,因此每个用户可以选择许多项目。

In the tutorial I have learned about @ManyToMany annotation. 在本教程中,我学习了@ManyToMany注释。

@Entity
public class Item extends Model {

    ...

    @ManyToMany(cascade = CascadeType.REMOVE)
    public List<User> users = new ArrayList<User>();

But second option I can think of is to define a separate class for User-to-Item relation so I can add additional information like date and time. 但我能想到的第二个选项是为User-to-Item关系定义一个单独的类,这样我就可以添加日期和时间等附加信息。

@Entity
public class ItemUserRel extends Model {
    @Id
    public Long id;

    public User user;
    public Item item;

    //additional information
    public Date date;

    ...

Which of both options is better design and why? 哪两种选择都是更好的设计,为什么?

I faced a similar issue a while ago. 我刚才遇到过类似的问题。 I also had to deal with a model User and the model Group . 我还必须处理模型User和模型Group My requirements were: 我的要求是:

A user can have n readable and n writable Groups. 用户可以具有n个 readablen writable组。 These permissions must be stored in a third table (not in User and not in Group table). 这些权限必须存储在第三个表中(不在用户而不在组表中)。 But also additional properties like authorisedBy and 'authorisedOn'. 还有其他属性,如authorisedBy和'authorisedOn'。 So @ManyToMany did not worked for, because I had no real control of it. 所以@ManyToMany没有工作,因为我没有真正的控制权。 Also the additional properties makes it hard to map via JPA. 此外,附加属性使得很难通过JPA进行映射。

Perhaps other designs are possible but I (still) think that introducing a new class UserGroup would be best. 也许其他设计是可能的,但我(仍然)认为引入一个新类UserGroup是最好的。 This class has @ManyToOne relation to a single User . 此类与单个User具有@ManyToOne关系。

I end up defining these three models: 我最终定义了这三个模型:

  1. User 用户
  2. Group - General information about the group model 组 - 有关组模型的一般信息
  3. UserGroup - Containing additional fields like: permissions , authorisedBy , authorisedOn etc. UserGroup - 包含其他字段,如: permissionsauthorisedByauthorisedOn等。

On my User model, I would have getter getUserGroups() but also getPersonalGroup() which is basically one (personal) instance of Group in getUserGroups() but where the createdBy and authorisedBy is the same user. 在我的用户模型,我会消气getUserGroups()getPersonalGroup()这基本上是一个(个人)的实例GroupgetUserGroups()但其中createdByauthorisedBy是相同的用户。

I found this design much more maintainable by me and more clear. 我发现这个设计更易于维护,更清晰。 Also this design helped me to create a comfortable user interface, where the administrator can manage and change permissions for UserGroups. 此设计也帮助我创建了一个舒适的用户界面,管理员可以在其中管理和更改UserGroup的权限。

Perhaps more useful information 也许更有用的信息

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

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