我有一个实体用户。我需要一个字段中的ManyToMany双向关系User-User对。我该怎么办?
@Entity
@Table(name = "users")
public class User {
@Id
private int id;
private Set<User> pairs;
}
我尝试过这样:
@ManyToMany
@JoinTable(name = "pairs", joinColumns = {
@JoinColumn(name = "a"),
@JoinColumn(name = "b")
})
private Set<User> pairs;
得到下一个结果:org.hibernate.AnnotationException: A Foreign key refering com.calm.model.entity.User from com.calm.model.entity.User has the wrong number of column. should be 1
ddl产生的db scmema:
CREATE TABLE `users` (
`id` int(11) NOT NULL,
...
PRIMARY KEY (`id`)
)
和期望对表:
CREATE TABLE `pairs` (
`a` int(11) NOT NULL, //user 1
`b` int(11) NOT NULL, //user 2
PRIMARY KEY (`a`,`b`)
)
预期的行为,例如:
SELECT b as id2 FROM pairs WHERE a = :id1
UNION
SELECT a as id2 FROM pairs WHERE b = :id1