我想执行嵌套连接,其中我的类用户将包含类似于SQL查询的用户列表:
SELECT user1.id, user2.id FROM ( users user1 LEFT JOIN friends friend ON user1.id=friend.who ) LEFT JOIN users user2 ON friend.with=user2.id GROUP BY user1.id, user2.id
我的用户实体类:
@Entity
@Table(name = "users")
public class User implements Serializable {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name = "id")
private Integer id;
@Column(name = "login")
private String login;
@Column(name = "name")
private String name;
@Column(name = "lastname")
private String surname;
@Column(name = "password")
private String password;
@ManyToMany
????
private List<User> users;
}
用户之间的关系 - FriendRelation实体类:
@Entity
@Table(name="friends")
public class FriendRelation implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id")
private Integer id;
@Column(name = "who")
private Integer who;
@Column(name = "with")
private Integer with;
@OneToMany
@JoinColumn(name="with", referencedColumnName = "id")
private List<User> users;
}
谁 - 指用户的身份
with - 指的是与用户谁
的朋友关系中的用户的ID
我应该用什么代替&#34; ????&#34;实现它?
我使用的是Spring Data JPA
答案 0 :(得分:1)
解决方案是添加注释@JoinTable
我们可以使用这个注释来使用映射表连接两个表,在这种情况下,它是反向连接。
@JoinTable(name = "friends", joinColumns = @JoinColumn(name = "who"), inverseJoinColumns = @JoinColumn(name = "with"))
用户类:
@Entity
@Table(name = "users")
public class User implements Serializable {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name = "id")
private Integer id;
@Column(name = "login")
private String login;
@Column(name = "name")
private String name;
@Column(name = "lastname")
private String surname;
@Column(name = "password")
private String password;
@ManyToMany
@JoinTable(name = "friends", joinColumns = @JoinColumn(name = "who"), inverseJoinColumns = @JoinColumn(name = "with"))
private List<User> friends;
}
Here完美地解释了如何处理这种情况 希望它可以帮到某人。