数据库中的表结构
数据库中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>