一对一映射
<resultMap type="com.samples.entity.User" id="resultMap3">
<id property="id" column="id" />
<result property="name" column="name" />
<!-- association :配置一对一属性 -->
<!-- javaType:属性类型 -->
<association property="dept" javaType="com.samples.entity.Dept">
<!-- id:声明主键-->
<id property="id" column="dId" />
<result property="name" column="dName" />
</association>
</resultMap>
<select id="selectAll" resultMap="resultMap3">
select u.*,d.id dId,d.name dName
from user u left join dept d on u.dept_id = d.id
</select>
若两个表有相同属性名,需要使用别名,否则会全注入前面的属性值
<resultMap id="userMap" type="com.samples.entity.User">
<id property="id" column="id"/>
<result property="name" column="name"/>
<association property="dept" column="dept_id"
select="com.samples.mapper.DeptMapper.selectById"/>
<association property="role" column="role_id"
select="com.samples.mapper.RoleMapper.get"/>
</resultMap>
<select id="get" resultMap="userMap">
select *
from user
where id = #{id}
</select>
select调用其他mapper方法
一对多映射
<resultMap type="com.samples.entity.Dept" id="deptMap1">
<id property="id" column="id" />
<result property="name" column="name" />
<!-- collection :配置一对多属性 -->
<!-- ofType:属性类型 -->
<collection property="userList" ofType="com.samples.entity.User" column="deptId">
<!-- id:声明主键-->
<id property="id" column="uId" />
<result property="name" column="uName" />
<result property="deptId" column="dept_id" />
<result property="roleId" column="role_id" />
</collection>
</resultMap>
<select id="findAll1" resultMap="deptMap1">
select d.* ,u.id uId,u.name uName,u.dept_id,u.role_id from dept d ,user u where d.id = u.dept_id
</select>
<resultMap type="com.samples.entity.Dept" id="deptMap2">
<id property="id" column="id" />
<result property="name" column="name" />
<!-- collection :配置一对多属性 -->
<!-- ofType:属性类型 -->
<collection property="userList" select="com.samples.mapper.UserMapper.findByDeptId" column="id" />
</resultMap>
<select id="findAll2" resultMap="deptMap2">
select * from dept
</select>