Spring JPA:如何获得定制的json响应

wfauudbj  于 2023-02-13  发布在  Spring
关注(0)|答案(3)|浏览(105)

我需要列出系统中所有可用的权限,并且在每个权限上,我需要向特定用户显示哪个权限在他身上是活动的......下面是表关系:

表中的所有记录:authority_master(从authority_master中选择 *)

表中的所有记录:用户权限关系(从用户权限关系中选择 *;)

表中的所有记录:用户详细信息(从用户详细信息中选择 *)

**预期JSON输出:**如果我想知道每个用户(基本上是表“user_authority_relation”中存在的记录)的哪些权限和所有权限处于活动状态,(这里我想列出表“authority_master”中可用的所有权限,并且只有当表“user_authority_relation”中存在特定权限时,“isActive”JSON键才为True

基本上,我需要选择用户详细信息表并与users_authority_relation连接,这将只给予谁有权限的结果,但它不会列出所有可用的权限。我对此感到困惑,如何获得如下预期的JSON结果x1c4d 1x

x7rlezfr

x7rlezfr1#

如果允许进行多个数据库调用,则可以执行此操作
1.从数据库中获取授权机构authList的列表。
1.获取用户列表
1.对每个用户执行步骤4-5
1.循环authList并检查当前用户的权限列表是否包含该元素。如果是,则设置isActive true,否则为false。
1.将authList设置为当前用户权限

lymnna71

lymnna712#

由于我也在Spring Boot 学习阶段,我发现你的问题很有趣,所以我试图解决你的问题
您的实体Bean可能如下所示
用户权限关系bean

@Table(name="user_authority_relation")
@Data
public class UserAuthRelation implements Serializable {

    @Id
    @GeneratedValue

    Long user_auth_id;

    @ManyToOne
    @JoinColumn(name="userid")
    UserDetails user;

    @JoinColumn(name="authorityid")
    @OneToOne
    AuthorityMaster authority;
    
}

UserDetailsBean.java

@Entity
@Table(name="userdetails")
@Data
public class UserDetails implements Serializable {

    @Id
    @GeneratedValue
    Long userid;
    String name;

    @OneToMany(mappedBy="user")
    List<UserAuthRelation> userAuths;
    
}

AuthorityMaster.java

@Entity
@Table(name="authority_master")
@Data
public class AuthorityMaster implements Serializable {

    @Id
    @GeneratedValue
    Long authorityid;
    String authority;
    String description;
    
    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        AuthorityMaster other = (AuthorityMaster) obj;
        if (authorityid == null) {
            if (other.authorityid != null)
                return false;
        } else if (!authorityid.equals(other.authorityid))
            return false;
        return true;
    }
    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((authorityid == null) ? 0 : authorityid.hashCode());
        return result;
    }

    
    
}

为了获得所需的响应,我们需要创建一些类,这些类可以帮助创建自定义响应bean,如下所示

@Data
public class CustomResponseJson implements Serializable {

    List<UserResponseJson> usersList;
    
}

@Data
public class UserResponseJson {
    Long userId;
    List<PermissionObject> permissions;
}

@Data
public class PermissionObject {
        String authority;
        Long authorityid;
        Boolean isactive;
}

休息控制器

@RestController
public class UsersController {

    @Autowired
    UserDetailRepository userRepo;
    @Autowired
    AuthorityRepository authRepo;
    
    @GetMapping("/fetchUserPermissons")
    @ResponseBody
    public CustomResponseJson fetchUserPermission() {

        //find all available users 
        List<UserDetails> users = userRepo.findAll();

        //find all available authorities
        List<AuthorityMaster> auths = authRepo.findAll();

        //initilizing custom reponse bean
        CustomResponseJson res =new CustomResponseJson();

        if(users!=null && !users.isEmpty()){

            //list of all users in json response
            List<UserResponseJson> userJsonReponse = new ArrayList<UserResponseJson>();

            for(UserDetails user : users){
                UserResponseJson userjson = new UserResponseJson();
                userjson.setUserId(user.getUserid());

                //prepare list of all authority availed and not availed to user
                List<PermissionObject> permissions = new ArrayList<PermissionObject>();
                if(user.getUserAuths()!=null && user.getUserAuths().size()>0){
                    List<AuthorityMaster> tempList = new ArrayList<AuthorityMaster>();
                    for(UserAuthRelation rel : user.getUserAuths()){
                        tempList.add(rel.getAuthority());
                        PermissionObject permObj = new PermissionObject();
                        permObj.setAuthority(rel.getAuthority().getAuthority());
                        permObj.setAuthorityid(rel.getAuthority().getAuthorityid());
                        permObj.setIsactive(true);
                        permissions.add(permObj);
                    }

                    //to find authority which is not assigned to user
                    List<AuthorityMaster> remainedAuths = auths.stream()
                          .filter(e -> !tempList.contains(e))
                          .collect (Collectors.toList());
                    for(AuthorityMaster auth:remainedAuths){
                        PermissionObject permObj = new PermissionObject();
                        permObj.setAuthority(auth.getAuthority());
                        permObj.setAuthorityid(auth.getAuthorityid());
                        permObj.setIsactive(false);
                        permissions.add(permObj);
                    }
                }
                userjson.setPermissions(permissions);
                userJsonReponse.add(userjson);
            }

            res.setUsersList(userJsonReponse);
        }
        return res;
    }

}

输出

umuewwlo

umuewwlo3#

您应该创建一个响应DTO,它可以保存来自不同资源(数据库、外部服务)的所有数据
我的控制器响应为:

@Data
@AllArgsConstructor
@NoArgsConstructor
public class AxeleStatisticReportDTO implements Serializable {

    private static final long serialVersionUID = 1L;
    private List<EmailLogDTO> emailAndCount = new ArrayList<>();
    private List<IpLogDTO> ipRequestsCount = new ArrayList<>();
}

相关问题