queryWrapper进行多对多关联

您所在的位置:网站首页 querywrapper多表查询分页 queryWrapper进行多对多关联

queryWrapper进行多对多关联

2023-05-17 21:30| 来源: 网络整理| 查看: 265

好的,假设我们有 user、role 和 user_role 三张表,它们各自的 bean 对象可以定义如下:

/** * 用户表 */ @Data @TableName("user") public class User { @TableId(type= IdType.AUTO) private Long id; private String username; private String password; private String name; private Integer age; private String email; @TableField(exist = false) private List roles; // 存储用户所拥有的角色信息 } //加上注解后,Mybatis Plus 就会忽略这个字段,不会尝试将其映射到数据库表中。这样,我们就可以使用 //setRoles() 方法将查询出来的角色信息设置到 User 对象中,并在业务中使用了。 // 角色表 @Data @TableName("role") public class Role { @TableId(type = IdType.AUTO) private Long id; private String name; private String description; } // 用户角色关联表 ,其实这个用不到 @Data @TableName("user_role") public class UserRole { @TableId(type = IdType.AUTO) private Long id; private Long userId; private Long roleId; }

其中,@TableName 注解用于指定实体类对应的数据库表名,@TableId 注解用于指定主键字段的属性名和类型。这些注解在 Mybatis Plus 中是非常常用的。

使用 Entity 实体类进行多表联接查询时,我们可以先查询某个实体类,并将其存入缓存中,然后再通过 selectList() 方法查询与其关联的实体类信息。例如,要查询某个用户所拥有的角色信息,可以使用如下代码:

public User getUserWithRoles(Long userId) { // 查询用户信息,并将其存储到缓存中 User user = userMapper.selectById(userId); // 查询用户对应的角色信息,并将其存储到缓存中 List roles = roleMapper.selectList( Wrappers.lambdaQuery() .inSql(Role::getId, "SELECT role_id FROM user_role WHERE user_id = " + userId)); // 将角色信息设置到用户对象中,并返回用户对象 user.setRoles(roles); return user; }

其中,通过 Wrappers.lambdaQuery() 创建了一个 LambdaQueryWrapper 对象,然后使用 .inSql(Role::getId, ...) 方法指定关联查询的条件。最后,将查询结果存储到缓存中,并将角色信息设置到用户对象中。



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3