您的位置:首页 > 其它

查询多对多关系映射文件如何处理

2020-03-29 13:00 232 查看

数据库中的表结构

数据库中user表,一个role表,一个中间表user_role
其中user_role表的内容是分别指向user表的id和role表的id

UID   RID
41    1
41    2
45    1

执行的操作是查询所有user表和对应的角色关系 ,如果用户没有角色就为null
关键的是resultMap,所有返回的数据都要有相应的数据接收,一张表resultMap
和两种表的区别是里层嵌套了。
其中type是表的路径由于在配置中写了扫描哪个包故可以用别名,还有一个混淆点是property和column,
其中property是实体类对应的,column是数据库中对应的,又由于windows下不区别大小写。

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.itheima.dao.IRoleDao">
<!-- 定义role表的RosultMap   -->
<resultMap id="roleMap" type="role">
<id property="roleId" column="id"></id>
<result property="roleName" column="role_name"></result>
<result property="roleDesc" column="role_desc"></result>
<collection property="users" ofType="user">
<id column="id" property="id"></id>
<result column="username" property="username"></result>
<result column="address" property="address"></result>
<result column="birthday" property="birthday"></result>
<result column="sex" property="sex"></result>
</collection>
</resultMap>
<select id="findAll" resultMap="roleMap">
select * from user u left join user_role ur on u.id = ur.uid  left join role r on r.id = ur.rid
</select>

</mapper>

转载大佬的多对多关系博客

  • 点赞
  • 收藏
  • 分享
  • 文章举报
qq_44801336 发布了54 篇原创文章 · 获赞 5 · 访问量 751 私信 关注
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: