<resultMap id="UserMap" type="User">
colum:数据库中的字段 property:实体类中的属性
<result colum="id" property="id"/>
<result colum="name" property="name"/>
<result colum="pwd" property="password"/>
</resultMap>
<select id="getUserById" resultMap="UserMap">
select * from user where id = #{id}
</select>
resultMap
元素是 MyBatis 中最重要最强大的元素。
resultMap
的设计思想是,对简单的语句做到零配置,对于复杂一点的语句,只需要描述语句之间的关系就行了
resultMap
最优秀的地方在于:虽然你已经对它相当了解了,但是根本就不需要显式地用到它们
【多对一】与【一对多】
多个学生,对应一个老师
对于学生这边而言:关联。多个学生关联一个老师【多对一】
对于老师而言,集合,一个老师有很多老师【一对多】
1、多对一:association
按照查询嵌套处理
<mapper namespace="com.bjpowernode.dao.StudentMapper">
<select id="getStudents" resultMap="StudentTeacher" >
select * from student
</select>
<resultMap id="StudentTeacher" type="Student">
复杂的属性,我们要单独处理,对象:association 集合:collection
property:实体类中的属性(外键) colum:表中的外键字段 javaType:java类型
<association property="teacher" column="tid" javaType="Teacher" select="getTeacher"/>
</resultMap>
<select id="getTeacher" resultType="teacher">
select * from teacher where id = #{tid}
</select>
</mapper>
按照结果嵌套处理(有点像联表查询)
<select id="getStudents2" resultMap="StudentTeacher2">
select s.id as sid,s.name as sname,t.name as tname
from student s join teacher t on s.tid = t.id
</select>
<resultMap id="StudentTeacher2" type="Student">
<result property="id" column="sid"/>
<result property="name" column="sname"/>
<association property="teacher" javaType="Teacher">
<result property="name" column="tname"/>
<result property="id" column="tid"/>
</association>
</resultMap>
2、一对多处理:collection
按照查询嵌套处理
<select id="findTeacher" resultMap="TeacherStudent2">
select * from teacher where id = #{tid}
</select>
<resultMap id="TeacherStudent2" type="Teacher">
<collection property="students" javaType="ArrayList" ofType="Student" column="id" select="getStudentByTid"/>
</resultMap>
<select id="getStudentByTid" resultType="Student">
select * from student where tid=#{tid}
</select>
按照结果嵌套处理
<select id="getTeacher" resultMap="TeacherStudents">
select t.id tid,t.name tname,s.id sid,s.name sname
from student s join teacher t on s.tid = t.id
where tid = #{tid};
</select>
<resultMap id="TeacherStudents" type="Teacher">
<result column="tid" property="id"/>
<result column="tname" property="name"/>
<collection property="students" ofType="Student">
<result property="name" column="sname"/>
<result property="id" column="sid"/>
<result property="tid" column="tid"/>
</collection>
</resultMap>
小结
1.关联-association 【多对一】
2.集合-collection【一对多】
3.javaType & ofType
1.javaType用来指定实体类中属性的类型
2.ofType用来指定映射到List或者集合中的pojo类型
注意:
1.保证SQL的可读性,尽量保证通俗易懂
2.注意一对多和多对一中,属性名字和字段的问题
3.如果问题不好排查错误,建议使用日志(Log4j)