【发布时间】:2020-08-02 09:13:23
【问题描述】:
简而言之,我尝试使用 Spring security 进行授权。但我得到错误
Caused by: java.lang.IllegalArgumentException: Not a managed type: class java.lang.Long
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'roleRepository': Invocation of init method failed;
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'userDetailsServiceImpl': Unsatisfied dependency expressed through field 'roleRepository';
接口 RoleRepository 实现来自 JpaRepository 的方法。
@Repository
public interface RoleRepository extends JpaRepository<Long, Roles>{
@Query("select r from roles r where id = 1")
public List<Roles> getRole(long userId);
}
它与 UserDetailsServiceImpl 类相关联,该类实现了 loadUserByUsername 方法。在这种方法中,我获取用户数据(角色、用户名、密码)。
我认为实体类(Roles、Users、UserRole)中的问题,我使用 OneToMany 绑定:UserRole 包含 user_id 和 role_id 字段,它们分别与 Users 和 Roles 表相关联。不明白,到底哪里出错了。
用户角色:
@Entity
@Table(name = "user_role")
public class UserRole {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "user_id", nullable = false)
private Users users;
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "role_id", nullable = false)
private Roles roles;
// getters, setters
}
角色:
@Entity
@Table(name = "roles")
public class Roles {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
@Column(name = "name")
private String name;
@OneToMany(mappedBy = "roles")
private Set<UserRole> roles;
// getters, setters
}
用户:
@Entity
@Table(name = "users")
public class Users {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long uid;
@Column(name = "username")
private String username;
@Column(name = "password")
private String password;
@Column(name = "enabled")
private boolean enabled;
@OneToMany(mappedBy = "users")
private Set<UserRole> users;
// getters, setters
}
【问题讨论】: