jhipster利用JDL文件生成User、Role、userRole的注意事项及操作方法

1、注意事项

  • 由于jhipster是自动创建SpringSecurity+jwt 项目,所以 会自动创建并管理 User实体类 & userJWTController ,在运行 jdl 文件时, 会自动跳过自定义编写的User类,执行其他语句。如果需要在jhipster 自动创建的User类中添加其他字段,则只能在事先生成的User.java源文件中手动编写添加其他属性和get/set方法。
  • role_code数据字段必须为String类型,且形式如ROLE_ADMIN,必须以ROLE_开头(SpringSecurity硬性要求)。

2、步骤

  • 拿到名为 mono1.jdl 的JDL文件后,Terminal 终端运行 jhipster jdl mono1.jdl 命令之后 ,我们需要:

1、在userRoleRepository这个仓库类中添加一条JPA原生查询语句

/*
通过userID获取roleCode
(roleCode 表示角色的英文名,比如ROLE_ADMIN,是String;
roleId 表示数据库表role的Id号,是Long)
*/
@Query("select r.roleCode from UserRole ur left join Role r on ur.roleId = r.id where ur.userId = ?1")
   List<String> getAllRoleCodeByUserId(Long userId);

2、在DomainUserDetailsService类中将原先对应的方法名相同的方法改为下面这个。
代码解析:入参是与数据库对应的user类对象,返回值是在SpringSecurity下的User类对象。即通过入参的user获取userId,进一步获取roleCode(在userRoleRepository类中写JPA原生关联查询语句一步到位),将String 类型的roleCode赋值给SimpleGrantedAuthority构造方法(为啥强调String类型的,因为不是String类型的它不要,可自行查看底层源码),之后形成的是 名为authorities 的 list集合。分别赋值给SpringSecurity 下的 User对应的属性并返回。

   private org.springframework.security.core.userdetails.User createSpringSecurityUser(User user) {
    
    
        List<GrantedAuthority> authorities = userRoleRepository
            .getAllRoleCodeByUserId(user.getId())
            //.findAllByUserId(user.getId())
            .stream()
            .map(roleCode->new SimpleGrantedAuthority(roleCode))
            //.map(userRole -> new SimpleGrantedAuthority(userRole.getRoleCode()))
            .distinct()
            .collect(Collectors.toList());
        return new org.springframework.security.core.userdetails.User(user.getLogin(), user.getPassword(), authorities);
    }

然后即可运行成功。

猜你喜欢

转载自blog.csdn.net/qq_45486709/article/details/123308596
今日推荐