XML映射是连接和操作数据库的第二种方法 第一种方法是通过注解也就是@Mapper注解来开发
XML映射文件的规范
- XML映射文件的名称要与Mapper接口名称一致 并且XML映射文件要和Mapper接口在相同包下(同包同名)
- XML映射文件的那么namespace属性要和Mapper接口全类名一致
- XML映射文件中sql语句的id要与Mapper接口中的方法名一致 并且返回类型一样
<?xml version="1.0" encoding="UTF-8" ?>
<!--mysql的约束文件-->
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.itheima.Mapper.EmpMapper">
<!-- resultType:单条记录返回的类型-->
<select id="selectEmpByCondition" resultType="com.itheima.pojo.Emp">
select * from emp where name like concat('%',#{name},'%') and gender = #{gender}
and entrydate between #{begin}
and #{end} order by update_time desc
</select>
</mapper>
动态SQL
1 if 用来做动态判断的标签
如果条件成立就拼接sql语句
<mapper namespace="com.itheima.Mapper.EmpMapper">
<!-- resultType:单条记录返回的类型-->
<select id="selectEmpByCondition" resultType="com.itheima.pojo.Emp">
select * from emp
<where>
<if test="name != null">
name like concat('%',#{name},'%')
</if>
<if test="gender != null">
and gender = #{gender}
</if>
<if test="begin != null and end != null ">
and entrydate between #{begin}
and #{end}
</if>
</where>
order by update_time desc
</select>
</mapper>
2.foreach循环遍历
<!-- 通过ID批量删除-->
<delete id="delectEmpsById">
delete from emp where id in
<!-- collection:集合名称 item:集合中元素的名称 open开始前拼接的sql语句: close:结束后拼接的sql语句 separator:集合元素之间的分隔符-->
<foreach collection="ids" item="id" open="(" close=")" separator=",">
#{id}
</foreach>
</delete>
3.sql和include标签