Self ManyToMany with additional columns using JPA 2.0
I want to create kind of "Friendship" relation between Users models. I also need an additional columns for every friendship. I know I need to use joining class with composite primary key. Thats my User class
public class User implements Serializable {
@Id
@Basic(optional = false)
@Column(name = "id")
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Integer id;
@OneToMany(mappedBy="friendA")
private Set<Friendship> friends;
I also have FriendshipId class
@Embeddable
public class FriendshipId implements Serializable {
private long friendAId;
private long friendBId;
}
And finally Friendship class
@Entity
@IdClass(FriendshipId.class)
public class Friendship implements Serializable {
private Integer friendAId;
private Integer friendBId;
@Basic(optional = false)
@Column(name="date_added")
@Type(type="org.jadira.usertype.dateandtime.joda.PersistentDateTime")
private DateTime date_added;
@ManyToOne
@PrimaryKeyJoinColumn(name="friendAId", referencedColumnName="friendAId")
private User friendA;
@ManyToOne
@PrimaryKeyJoinColumn(name="friendBId", referencedColumnName="friendBId")
private User friendB;
}
This seems to work but database table generated in my database consists every ID twice - I guess one set is for primary key and second for foreign keys.
How can I make this PK unique - that Friendship of A to B will be rejected if there is B to A one?
Another question is about a design - is this a good way to achieve what I want to achieve? I me开发者_JAVA百科an using composite key instead of simply own pk for Friendship.
I guess in Friendship entity you added User entity twice (very fine) but why
private Integer friendAId;
private Integer friendBId;
again there? That could be cause of ID getting generated twice.
精彩评论