下列代码中:
1 resultMap 里面property对应实体类属性,column对应数据库字段名
2 主键用 id 标签 其他用result
3 关联查询(子查询和连接查询) 连接查询查一次
4 一个年级多个学生,所以用collection 如果一对一用association
<?xml version="1.0" encoding="UTF-8" ?>
<!--指定约束文件:定义和限制当前文件中可以使用的标签和属性,以及标签出现的顺序
mybatis-3-mapper.dtd 约束文件名称
-->
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.tmg.dao.TypeDao">
<resultMap id="typeMap" type="com.tmg.domain.Type">
<id property="id" column="type_id"></id>
<result property="name" column="type_name"></result>
<!-- 连接查询-->
<!-- <collection property="students"-->
<!-- javaType="java.util.List" ofType="com.tmg.domain.Student">-->
<!-- <id property="id" column="stu_id" javaType="java.lang.Integer"></id>-->
<!-- <result property="name" column="stu_name"></result>-->
<!-- <result property="age" column="stu_age"></result>-->
<!-- <result property="email" column="stu_email"></result>-->
<!-- </collection>-->
<!-- 子查询-->
<collection property="students" column="type_id"
javaType="java.util.List" ofType="com.tmg.domain.Student"
select="com.tmg.dao.StudentDao.selectByTypeId">
</collection>
<!-- property 实体类中的属性名 column 子查询使用的字段 javaType 集合类型 ofType 集合里面的泛型类型-->
</resultMap>
<select id="selectAll" resultMap="typeMap">
select s.*,t.* from student s join student_type t on s.type_id=t.type_id
</select>
<select id="selectById" resultMap="typeMap">
select * from student_type where type_id=#{id}
</select>
</mapper>