[英]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. 在我的应用程序中,我有不同的
User
和Item
,因此每个用户可以选择许多项目。
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个
readable
和n 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: 我最终定义了这三个模型:
permissions
, authorisedBy
, authorisedOn
etc. permissions
, authorisedBy
, authorisedOn
等。 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()
这基本上是一个(个人)的实例Group
在getUserGroups()
但其中createdBy
和authorisedBy
是相同的用户。
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.