resultMap
1)自定义resultMap,实现高级结果集映射
2)id :用于完成主键值的映射
3)result :用于完成普通列的映射
4)association :一个复杂的类型关联;许多结果将包成这种类型
5)collection : 复杂类型的集
使用方式
1.select标签 定义resultMap 注意不是 resultType
<select id="selectDE" resultMap="selectDE"> select d.deptid,d.deptname dname ,d.deptadress daddress,e.ename,e.ejob from dept d,empinfo e where d.deptid = e.dpet </select>2.resultMap标签 id为 selec标签中定义的 resultMap的值 type 是这个结果集最终返回的类型的最小单位
<resultMap id="selectDE" type="com.mybatis.pojo.Dept"> <result column="dname" property="dname"></result> <result column="deptid" property="deptid"></result> <result column="daddress" property="daddress"></result> </resultMap>3.result 标签 column 是 数据库中查询出来的字段名 property: 如果resultMap的type是对象 则property是对象中对应的属性名 注意: 如果数据库的字段和实体类对象中的属性名完全相同 可不必配置result,否则 必须使用result一一对应
<result column="dname" property="dname"></result> <result column="deptid" property="deptid"></result> <result column="daddress" property="daddress"></result>2 association 分布查询 代码如下:
<!-- association 分步查询--> <resultMap id="selectEmpresED" type="com.mybatis.pojo.Emp"> <result column="ename" property="ename"></result> <result column="ejob" property="ejob"></result> <association property="dept1" column="dpet" select="com.mybatis.mapper.EmpMapper.selectDept" fetchType="lazy"> <!--<id column="dpet" property="deptid"></id>--> <result column="deptname" property="dname"></result> <result column="deptadress" property="daddress"></result> </association> </resultMap> <select id="selectEmpresED" resultMap="selectEmpresED"> select ename,ejob,dpet FROM empinfo; </select> <select id="selectDept" resultType="com.mybatis.pojo.Dept"> select deptid,deptname dname ,deptadress daddress from dept where deptid = #{deptid} </select> 分步详解: 1.先查询主表的字段 以及 外键 主查询语句设为 resultMap 2.编写结果集 <resultMap 可复用是mybatis的强大之处> 3.association 中 property 对应 对象中的对象 column 对应sql中的外键字段 4.id标签可保证数据的完整性 否则可能会屏蔽相同数据