我是靠谱客的博主 魁梧蛋挞,这篇文章主要介绍mysql一对多嵌套查询,现在分享给大家,希望可以做个参考。

在Vo对象中,有时会用List<其他类属性> xxx来作为属性,这时需要嵌套查询

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
/** * Vo,通过此对象封装角色以及角色对应的菜单id * @author DELL */ @Data @ToString public class SysRoleMenuVo { /**角色id*/ private Integer id; /**角色名称*/ private String name; /**角色备注*/ private String note; /**角色对应的菜单id*/ private List<Integer> menuIds; }

除menuIds外,其他数据可以通过自身表查询

复制代码
1
2
3
4
<select id="findObjectById" resultMap="sysRoleMenuVo" parameterType="int"> select id,name,note from sys_roles where id = #{id} </select>

但是需要查询List menuIds,故嵌套查询
需要注意的是property属性和Vo对象属性一致,column属性是sql嵌套查询的条件,即以id为查询条件的。
若是上面的条件与下面的属性名不一致可以使用别名

上面的查询中使用别名 role_nam as name
下面用 < result column=“role_name” property=“name”/>

复制代码
1
2
3
4
5
<resultMap id="SysRoleMenuVo" type="com.cy.pj.common.vo.SysRoleMenuVo"> <collection property="menuIds" column="id" select="com.cy.pj.sys.dao.SysRoleMenuDao.findMenuIdsByRoleId"> </collection> </resultMap>

为了体现功能模块划分,将嵌套查询的sql写到对应的xml中
通过角色id查询菜单id,且菜单id不止一个

复制代码
1
2
3
4
<select id="findMenuIdsByRoleId" parameterType="int" resultType="int"> select menu_id from sys_role_menus where role_id = #{id}; </select>

经过一系列努力以为结束了,但是一测方法发现

id等于null

复制代码
1
2
SysRoleMenuVo(id=null, name=总监, note=否则解决重点问题bug, menuIds=[8, 24, 25, 45, 119, 126, 127, 46, 115, 116, 117, 118, 47, 120, 128, 130, 48, 132])

原因是id需要查询,但是没有专门去做映射是没有值的
需要加上
< id column=“id” property=“id”/> property与类中属性一致,需要用到类的setter方法—亲测 column与嵌套查询的条件也就是主表有关,可以改 只需要主表使用别名就能改

复制代码
1
2
3
4
5
6
7
8
9
10
<select id="findObjectById" resultMap="SysRoleMenuVo" parameterType="int"> select id ,name,note from sys_roles where id = #{id} </select> <resultMap id="SysRoleMenuVo" type="com.cy.pj.common.vo.SysRoleMenuVo"> <id column="id" property="id"/> <collection property="menuIds" column="id" select="com.cy.pj.sys.dao.SysRoleMenuDao.findMenuIdsByRoleId"> </collection> </resultMap>

最后

以上就是魁梧蛋挞最近收集整理的关于mysql一对多嵌套查询的全部内容,更多相关mysql一对多嵌套查询内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(74)

评论列表共有 0 条评论

立即
投稿
返回
顶部