I have two entity,one of them(the Task) own two refers of another entity(The user).
public class Task{
private int id;
private User publisher;
private List<User>开发者_开发问答; manager;
}
public User{
private int id;
private String name;
private List<Task> tasks;
}
At the Task side,I can set "one-to-one" to "publisher",and "one-to-many" to "manager",but how to set the mapping in the user side?
It depends on what you want to have in the database.
If you want to have a separate foreign key for publisher
and join table for manager
, the easiest way to map the other side it this:
public class Task{
@ManyToOne
private User publisher;
@ManyToMany
private List<User> manager;
...
}
public User{
@OneToMany(mappedBy = "publisher")
private List<Task> publishedTasks;
@ManyToMany(mappedBy = "manager")
private List<Task> managedTasks;
...
}
If you actaully need a single list of tasks in User
, you can create it programmatically.
Alternatively, you can have a single join table with an additional Role
property:
public enum Role { PUBLISHER, MANAGER }
public class Task{
@ManyToMany
@MapKeyEnumerated
private Map<Role, User> participants;
...
}
public User{
@ManyToMany(mappedBy = "participants")
private List<Task> tasks;
...
}
Also think whether you need this relationship to be bidirectional at all. It looks like there are not so many use cases when you need a list of all tasks where a particular user participate. Perhaps you don't need this relationship at the User
side at all, and can use queries instead.
精彩评论