正如标题所示,我试图通过使用以下查询来选择用户名和角色名称。
select u.username, r.name
from users u, role r
inner join users_roles ur
on ur.user_id = u.id
where username = ?;
但是我收到以下错误
[2017-04-05 21:34:49] [42P01] ERROR: invalid reference to FROM-clause entry for table "u"
[2017-04-05 21:34:49] Hint: There is an entry for table "u", but it cannot be referenced from this part of the query.
[2017-04-05 21:34:49] Position: 79
我的用户实体如下
@Entity(name = "users") // Postgres doesn't like the table name "user"
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
private String username;
...
@ManyToMany
@JoinTable(
name = "users_roles",
joinColumns = @JoinColumn(
name = "user_id", referencedColumnName = "id"),
inverseJoinColumns = @JoinColumn(
name = "role_id", referencedColumnName = "id"))
private Collection<Role> roles;
...
我的角色实体如下
@Entity
public class Role {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
private String name;
@ManyToMany(mappedBy = "roles")
private Collection<User> users;
...
关于我做错了什么的线索?
答案 0 :(得分:0)
SELECT users.username, role.name
FROM users
LEFT OUTER JOIN users_roles
ON users.id = users_roles.user_id
LEFT OUTER JOIN role
ON users_roles.role_id = role.id
WHERE username = ?