一对一:
一、子查询
<select id="getStudent" resultMap="StudentMap">
select * from mybatis.student
</select>
<resultMap id="StudentMap" type="Student">
<!--复杂的属性要单独处理
如果是对象用association
集合使用collection-->
<association property="teacher" column="tid" javaType="Teacher" select="getTeacherById"/>
</resultMap>
<select id="getTeacherById" resultType="Teacher">
select * from mybatis.teacher where id=#{dsd}
</select>
teacher属性通过association里面又关联一个select来查询,并将student表查询出来的tid传入作为查询条件id,可以看成如下sql语句:
select * from teacher where id in (select tid from student)
二、连表查询
<select id="getStudent2" resultMap="StudentMap2">
select s.id sid,s.name sname,t.name tname,t.id tid
from mybatis.student s ,mybatis.teacher t
where s.tid=t.id
</select>
<resultMap id="StudentMap2" type="Student">
<result column="sid" property="id"/>
<result column="sname" property="name"/>
<association property="teacher" column="tname" javaType="Teacher">
<result column="tname" property="name"/>
<result column="tid" property="id"/>
</association>
</resultMap>
直接用一条sql语句连表查询将所要的内容全查出来,然后再用resultMap进行映射
一对多
1.连表查询
<select id="getTeacher" resultMap="TeacherMap">
select t.id tid ,t.name tname ,s.id sid,s.name sname
from mybatis.teacher t,mybatis.student s
where t.id=#{tid};
</select>
<resultMap id="TeacherMap" type="Teacher">
<result column="tid" property="id"/>
<result column="tname" property="name"/>
<!-- 集合用collection
List集合中的泛型信息,用ofType-->
<collection property="students" ofType="Student">
<result property="name" column="sname"/>
<result property="id" column="sid"/>
<result property="tid" column="tid"/>
</collection>
</resultMap>
注意要用collection
2.子查询
<select id="getTeacher2" resultMap="TeacherMap2">
select * from mybatis.teacher where id=#{tid}
</select>
<resultMap id="TeacherMap2" type="Teacher">
<collection property="students" javaType="ArrayList" ofType="Student" select="Student" column="id">
</collection>
</resultMap>
<select id="Student" resultType="Student">
select * from mybatis.student where tid=#{ ddd}
</select>
</mapper>
注意javaType ofType
javaType:用来指定实体类中属性的类型
ofType:用来映射到List或集合中的pojo类型,泛型的约束类型
associate用来一对一和多对一,collection用来一对多
一对一,一对多,多对一:
一个用户有一个角色,多个用户可以是相同的角色,一个角色可以有多个用户