无法使用spring security、jpa和hibernate从数据库中获取多对多关联中的角色

vdzxcuhz  于 2021-09-30  发布在  Java
关注(0)|答案(0)|浏览(210)

我正在尝试开发一个小型应用程序,使用SpringBoot+SpringSecurity作为后端(使用jpa和hibernate作为持久化的一方),angular作为前端。我正处于登录/注册用户阶段,在前端一切都很好;正确的数据正在到达后端。只是在尝试通过安全性时,事情不起作用,因为我无法正确地从数据库获取角色。我对spring security有点陌生,所以请容忍我。我在我的用户和角色类中使用多对多关联:

@Entity
public class User implements UserDetails {

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

    private String username;
    private String password;
    private String email;
    private boolean enabled;
    // bi-directional many-to-many association to Role
    @JsonIgnore
    @ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
    @JoinTable(name = "user_role", joinColumns = { @JoinColumn(name = "USER_ID", referencedColumnName = "id") }, inverseJoinColumns = { @JoinColumn(name = "ROLE_ID", referencedColumnName = "id") })
    private Set<Role> roles = new HashSet<>();

    @Override
    public boolean isAccountNonExpired() {
        return false;
    }

    @Override
    public boolean isAccountNonLocked() {
        return false;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return false;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        List<GrantedAuthority> authorities = new ArrayList<>();
        for (Role role: this.getRoles()) {
            SimpleGrantedAuthority authority = new SimpleGrantedAuthority(role.getName());
        }
        return authorities;
    }

//constructors

//getters and setters

我的角色课:

@Entity
public class Role implements Serializable {
    private static final long serialVersionUID = 1L;
    public static final String USER = "USER";
    public static final String ROLE_USER = "ROLE_USER";
    public static final String ROLE_ADMIN = "ROLE_ADMIN";
    public static final String ROLE_MODERATOR = "ROLE_MODERATOR";

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

    private String name;

    // bi-directional many-to-many association to User
    @ManyToMany(mappedBy = "roles", fetch = FetchType.LAZY, cascade = CascadeType.ALL)
    private Set<User> users = new HashSet<>();

//constructors

//getters and setters

我的用户报告:

public interface UserRepositorio extends JpaRepository<User, Long> {

    @Query("SELECT u FROM User u JOIN FETCH u.roles WHERE u.email = :email")
    public User getUserByEmail(@Param("email") String email);

}

如您所见,我正试图按照其他来源使用fetch指令,作为处理多对多关系的最佳方式;通过不在多对多注解中直接使用fetch=fetchtype.eager,避免将来出现性能问题。
但是,我试过fetchtype.eager。我用过集合,我用过列表。什么都不管用。
我可以很好地创建用户和角色-在我的数据库中生成一个user_role表,并且enteties被正确地持久化。
我正在我的主应用程序中创建用户,实现commandlinerunner界面,只是为了测试:

@Override
    public void run(String... args) {
        Set<Role> roles = new HashSet<>();
        Role roleUser = new Role(Role.ROLE_USER);
        Role roleAdmin = new Role(Role.ROLE_ADMIN);
        roles.add(roleUser);
        roles.add(roleAdmin);
        userService.saveUser(new User("user1", passwordEncoder.encode("1234"), "miguel@gmail.com", roles, true));
    }

以下是我尝试获取数据时的控制台输出:

2021-06-07 09:29:26.121 DEBUG 12672 --- [nio-8080-exec-1] org.hibernate.SQL                        : select user0_.id as id1_1_0_, role2_.id as id1_0_1_, user0_.email as email2_1_0_, user0_.enabled as enabled3_1_0_, user0_.password as password4_1_0_, user0_.username as username5_1_0_, role2_.name as name2_0_1_, roles1_.user_id as user_id1_2_0__, roles1_.role_id as role_id2_2_0__ from user user0_ inner join user_role roles1_ on user0_.id=roles1_.user_id inner join role role2_ on roles1_.role_id=role2_.id where user0_.email=?

2021-06-07 09:29:26.124 TRACE 12672 --- [nio-8080-exec-1] o.h.type.descriptor.sql.BasicBinder      : binding parameter [1] as [VARCHAR] - [miguel@gmail.com]
2021-06-07 09:29:26.127 TRACE 12672 --- [nio-8080-exec-1] o.h.type.descriptor.sql.BasicExtractor   : extracted value ([id1_1_0_] : [BIGINT]) - [1]
2021-06-07 09:29:26.127 TRACE 12672 --- [nio-8080-exec-1] o.h.type.descriptor.sql.BasicExtractor   : extracted value ([id1_0_1_] : [BIGINT]) - [1]
2021-06-07 09:29:26.130 TRACE 12672 --- [nio-8080-exec-1] o.h.type.descriptor.sql.BasicExtractor   : extracted value ([email2_1_0_] : [VARCHAR]) - [miguel@gmail.com]
2021-06-07 09:29:26.132 TRACE 12672 --- [nio-8080-exec-1] o.h.type.descriptor.sql.BasicExtractor   : extracted value ([enabled3_1_0_] : [BOOLEAN]) - [true]
2021-06-07 09:29:26.132 TRACE 12672 --- [nio-8080-exec-1] o.h.type.descriptor.sql.BasicExtractor   : extracted value ([password4_1_0_] : [VARCHAR]) - [$2a$10$RzPzVJMpfz8qMd0xspx3U.9aDyWRWvYw7tbcL8z/03MbFDmNyq99K]
2021-06-07 09:29:26.132 TRACE 12672 --- [nio-8080-exec-1] o.h.type.descriptor.sql.BasicExtractor   : extracted value ([username5_1_0_] : [VARCHAR]) - [user1]

提前谢谢你!

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题