Precautions and operation methods of jhipster using JDL files to generate User, Role, userRole

1. Matters needing attention

  • Since jhipster automatically creates the SpringSecurity+jwt project, it will automatically create and manage the User entity class & userJWTController. When running the jdl file, it will automatically skip the custom written User class and execute other statements. If you need to add other fields to the User class automatically created by jhipster, you can only manually add other attributes and get/set methods in the User.java source file generated in advance.
  • The role_code data field must be of String type, and the form is ROLE_ADMIN, and it must ROLE_start with (a mandatory requirement of Spring Security).

2. Steps

  • After getting the JDL file named mono1.jdl, after running jhipster jdl mono1.jdlthe command , we need to:

1. userRoleRepositoryAdd a JPA native query statement to this warehouse class

/*
通过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. In DomainUserDetailsServicethe class, change the corresponding method with the same name to the following.
Code analysis: The input parameter is the user class object corresponding to the database, and the return value is the User class object under Spring Security. That is, the userId is obtained through the input user, and the roleCode is further obtained ( userRoleRepositorywrite the JPA native association query statement in the class in one step), and the roleCode of the String type is assigned to the SimpleGrantedAuthorityconstructor (why emphasize the String type, because it is not a String type, it does not need , you can view the underlying source code by yourself), and then a list collection named authorities is formed. Assign values ​​to the properties corresponding to the User under SpringSecurity and return them.

   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);
    }

Then it can run successfully.

Guess you like

Origin blog.csdn.net/qq_45486709/article/details/123308596