XML映射文件(简单的SQL用注解,复杂的用xml)
规范:
XML映射文件的名称和Mapper接口名称一样(同包同名)注意:不能直接用.创建文件夹,用/分层
xml映射文件的namespace属性为mapper接口全限定名一致
xml映射文件的sql语句和mapper接口的方法名一致,并保持返回类型一致
xml约束
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd">
示例
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.example.demo.mapper.EmpMapper"><select id="select" resultType="com.example.demo.pojo.Emp">
-- resultType 单条记录封装的类型select * from emp where username like concat('%',#{name},'%') and gender = #{gender} order by create_time desc</select>
</mapper>
namespace
MybatisX 插件
快速定位 方便
ctrl+ALT+L SQL语句格式化(好用)
Mybatis 动态SQL
动态SQL :if 标签
示例1
查找的时候没输入条件则全部查找
select * from emp where username like concat('%',#{name},'%') and gender = #{gender} order by create_time desc
where标签可以自动去除sql中的 and where
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.example.demo.mapper.EmpMapper"><select id="select" resultType="com.example.demo.pojo.Emp">
-- resultType 单条记录封装的类型select * from emp<where><if test="name != null and name!= ''">username like concat('%',#{name},'%')</if><if test="gender != null">and gender = #{gender}</if></where>order by create_time desc</select>
</mapper>
示例2
更新时候如果没传值会变成null -->有值更新无值不更新
set标签 能去掉sql里面的,
update emp set username =#{username},image = #{image},update_time =#{updateTime} where id =#{id}
<update id="update">update emp<set><if test="username != null">username=#{username},</if><if test="image != null">image = #{image},</if><if test="updateTime != null">update_time =#{updateTime}</if></set>where id = #{id}</update>
动态SQL :foreach 标签
批量删除
delete from emp where id in(9,10,11);
<delete id="deleteByIds">deletefrom empwhere id in<!--collection 遍历的集合item 遍历出的元素separator 分隔符open 遍历开始片接前的SQL片段close 遍历开始片接后的SQL片段--><foreach collection="ids" item="id" separator="," open="(" close=")">#{id}</foreach></delete>
重复的sql片段
<sql id="xxx">
</sql>
<include refid="xxx">
</include>