I am creating a kind of social network and I have users that can follow other users. So I have an entity like:
@Entity
public class FollowedUser{
@ManyToOne
private User user;
@ManyToOne
private User followedUser;
//more fields
...
}
I cannot have a ManyToMany relationship as I have more fields in my FollowedUser entity. Now, the questions I have are:
- Should I use a compound key or a generated id (surrogate key)? I have read the following links (1, 2, 3) about the topic where a surrogate key is suggested, but I don't know if they apply to my concrete case (where my compound key would be composed of two surrogate foreign keys). Also here (4) it says "Composite primary keys typically arise when mapping from legacy databases" so I suppose they are discouraged.
- In case I should use a compound key, I don't know if I should use @IdClass (as recommended here 5) or @EmbeddedId (as recommended here 6) or any other option. Although I suppose it doesn't matter.
- In case I should use a surrogate key, I don't know how to still make impossible to have the compound candidate key repeated. I have read here (7) about unique indexes but I don't know if it is the correct workaround to that problem.