联表查询
创建数据库  
多对一处理(关联 association)
创建实体类 

 
 
一对多处理(集合 collection)

按查询嵌套处理
<select id="getTeacher" resultMap="TeacherMap">
select * from teacher where id=#{tid}
</select>
<resultMap id="TeacherMap" type="teacher">
<result property="id" column="id"></result>
<result property="name" column="name"></result>
<collection property="students" column="id" javaType="ArrayList" ofType="Student" select="getStudent">
</collection>
</resultMap>
<select id="getStudent" resultType="student">
select * from student where tid=#{id}
</select>
按结果嵌套处理
<select id="getTeacher2" resultMap="teacherMap2">
select s.id sid,s.name sname,t.id tid,t.name tname
from student s,teacher t
where s.tid=t.id and t.id=#{tid}
</select>
<resultMap id="teacherMap2" type="teacher">
<result property="id" column="tid"></result>
<result property="name" column="tname"></result>
<collection property="students" javaType="ArrayList" ofType="student">
<result property="id" column="sid"></result>
<result property="name" column="sname"></result>
<result property="tid" column="tid"></result>
</collection>
</resultMap>
测试;  

动态sql
   注:这里id类型写错了,应该为string
tip:编写一个IDUtils工具类,用于随机生成ID

tip:要解决pojo中驼峰命名法属性名和数据库下划线命名法字段名不一致的问题(数据库采用下划线命名是因为数据库会将字段名全部转换为大写,所以用下划线命名) 在mybatis配置文件setting中配置

if标签

传入参数类型为map,如上述的title和author就是map中的key;#{title}就是对应的value
choose 标签
choose when otherwise相当于java中的switch case default 
trim(where set)标签
 

trim可以定制化where和set,不过用的也不多,需要时参考文档即可
调用举例


sql片段
 
foreach 标签

collectin:map中传入的用于遍历的集合 item:集合中的每一项 index:下标,一般不用 open:开始符号 close:结束符号 separator:每一项中间的分隔符
foreach常用于in/or查询
举例如下
or查询
<select id="BlogForEach" parameterType="map" resultType="blog">
select * from blog
<where>
<foreach collection="ids" item="id" open="(" close=")" separator="or">
id=#{id}
</foreach>
</where>
</select>
in查询
<select id="BlogForEach" parameterType="map" resultType="blog">
select * from blog where id in
<foreach collection="ids" item="id" open="(" close=")" separator=",">
#{id}
</foreach>
</select>
 
|