2017-08-21 41 views
0

我試着通過實體通過@ManyToMany加載角色的用戶身份驗證,但我得到異常。如何通過spring-data爲@ManyToMany加載提取select?

ERROR: column user0_.role_id does not exist 

我剛開始學習spring數據。請幫我解決這個問題。謝謝。

用戶實體:

@Entity(name = "users") 
public class User implements UserDetails { 

    @Id 
    @GeneratedValue(strategy = GenerationType.IDENTITY) 
    private int id; 

    @Column(name = "username") 
    private String username; 

    @Column(name = "password") 
    private String password; 

    @Column(name = "role_id") 
    private int roleId; 

    @ManyToMany(fetch = FetchType.EAGER) 
    @JoinTable(name = "user_id_role_id" 
      , 
      joinColumns = { 
        @JoinColumn(name = "user_id", 
          nullable = false, 
          updatable = false) 
      }, 
      inverseJoinColumns = { 
        @JoinColumn(name = "role_id", 
          nullable = false, 
          updatable = false) 
      } 
    ) 
    private List<Role> authorities; 

    @Column(name = "account_non_expired") 
    private boolean accountNonExpired; 

    @Column(name = "account_non_locked") 
    private boolean accountNonLocked; 

    @Column(name = "credentials_non_expired") 
    private boolean credentialsNonExpired; 

    @Column(name = "enabled") 
    private boolean enabled; 
... 

而且角色實體:

@Entity(name = "user_role") 
public class Role implements GrantedAuthority { 

    @Id 
    @GeneratedValue(strategy = GenerationType.IDENTITY) 
    private int id; 

    @Column(name = "role") 
    private String role; 
... 

我的PostgreSQL模式:

CREATE TABLE IF NOT EXISTS user_role (
    id SERIAL PRIMARY KEY, 
    role VARCHAR(10) NOT NULL 
); 

CREATE TABLE IF NOT EXISTS users (
    id      SERIAL PRIMARY KEY, 
    username    VARCHAR(20) UNIQUE NOT NULL, 
    password    VARCHAR(20) UNIQUE NOT NULL, 
    account_non_expired  BOOLEAN   NOT NULL DEFAULT TRUE, 
    account_non_locked  BOOLEAN   NOT NULL DEFAULT TRUE, 
    credentials_non_expired BOOLEAN   NOT NULL DEFAULT TRUE, 
    enabled     BOOLEAN   NOT NULL DEFAULT TRUE 
); 

CREATE TABLE user_id_role_id (
    id  SERIAL PRIMARY KEY, 
    user_id INTEGER NOT NULL, 
    role_id INTEGER NOT NULL, 
    FOREIGN KEY (role_id) REFERENCES user_role (id), 
    FOREIGN KEY (user_id) REFERENCES users (id) 
); 

回答

2

錯誤表明您沒有在表用戶屬性ROLE_ID。 你有這樣的屬性在實體:

@Column(name = "role_id") 
private int roleId; 

但是當你創建表:

CREATE TABLE IF NOT EXISTS users (
    id      SERIAL PRIMARY KEY, 
    username    VARCHAR(20) UNIQUE NOT NULL, 
    password    VARCHAR(20) UNIQUE NOT NULL, 
    account_non_expired  BOOLEAN   NOT NULL DEFAULT TRUE, 
    account_non_locked  BOOLEAN   NOT NULL DEFAULT TRUE, 
    credentials_non_expired BOOLEAN   NOT NULL DEFAULT TRUE, 
    enabled     BOOLEAN   NOT NULL DEFAULT TRUE 
); 

你沒有財產ROLE_ID。

剛從用戶實體中刪除屬性roleId,它應該工作:)

+0

看起來像我的大腦一些重載。謝謝!這是最好的回答:) – Pavel