我使用mybatis-mp框架进行开发,框架的url是[这里](https://github.com/mybatis-mp)。
框架版本:1.5.8
VO课程
@Data
@ResultEntity(SysUser.class)
public class SysUserVo {
private Integer id;
private String userName;
private Integer roleId
@ResultEntityField(property = "password")
private String pwd;
@Fetch(source = SysUser.class, property = "roleId", target = SysRole.class, targetProperty = "id")
private SysRoleVo sysRole;
}
查询码
List<SysUserRoleVO> list = QueryChain.of(sysUserMapper)
.like(SysUser::getUser,"ad")
.returnType(SysUserRoleVO.class)
.list();
我想在 SysRole.type = 1 时加载 SysRole,我该怎么办?
您可以使用自定义查询或修改“@Fetch”注释逻辑。 “mybatis-plus”不直接支持注释中的条件获取,因此您需要在查询逻辑中处理这个问题。我假设您有 SysRole 的映射器。如果是这样,请获取“type = 1”的所有角色,然后在“SysUserVo”对象中手动设置“SysRole”字段。它应该看起来像这样:
@Mapper
public interface SysRoleMapper {
@Select("SELECT * FROM sys_role WHERE type = 1")
List<SysRole> selectActiveRoles();
}
List<SysUserVo> list = QueryChain.of(sysUserMapper)
.like(SysUser::getUser, "ad")
.select(SysUser::getId, SysUser::getUserName, SysUser::getRoleId)
.list();
List<SysRole> activeRoles = sysRoleMapper.selectActiveRoles();
Map<Integer, SysRole> roleMap = activeRoles.stream().collect(Collectors.toMap(SysRole::getId, Function.identity()));
list.forEach(user -> {
SysRole role = roleMap.get(user.getRoleId());
if (role != null) {
user.setSysRole(new SysRoleVo(role));
}
});