场景
在实际的开发过程中,往往会从多个表里获取数据。此时需要用到多表操作。如查询用户的个人信息及部门信息。
实例
UserMapper.java
public interface UserMapper {
UserInfo getUserInfoById (Integer id);
}
DepartmentMapper.java
public interface DepartmentMapper {
Department getDepartmentByUserId (Integer uid);
}
UserMapper.xml
<select id="getUserInfo" resultMap="userInfoMap">
SELECT username, age, workno, deptid
FROM user WHERE uid = #{id}
</select>
<resultMap id="userInfoMap" type="com.cat.pojo.UserInfo">
<result column="username" property="uname"/>
<result column="age" property="age"/>
<result column="workno" property="workNo"/>
<!-- 将查询出来的User对象的deptid传入,封装成具体的Department信息,得到用户的信息及Department信息 -->
<association property="dept" column="deptid" select="com.cat.mapper.DepartmentMapper.getDepartmentByUserId" />
</resultMap>
DepartmentMapper.xml
<select id="getDepartmentByUserId" parameterType="string" resultType="com.cat.pojo.Department">
SELECT department_name, leader FROM department WHERE id = #{deptId}
</select>
SQL执行过程
此时数据的查询将会分为两步,第一步将用户检索出来,第二步再根据每个用户的deptid查询到部门信息。
网友评论