In my app I have different User
s and Item
s, so each user can pick many items.
In the tutorial I have learned about @ManyToMany
annotation.
@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.
@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
. My requirements were:
A user can have n readable
and n writable
Groups. 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'. So @ManyToMany did not worked for, because I had no real control of it. Also the additional properties makes it hard to map via JPA.
Perhaps other designs are possible but I (still) think that introducing a new class UserGroup
would be best. This class has @ManyToOne
relation to a single User
.
I end up defining these three models:
permissions
, authorisedBy
, authorisedOn
etc. 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.
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.
Perhaps more useful information
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.