MyBatis 动态SQL
动态SQL是指在业务处理过程中根据不同的条件 动态地拼接SQL语句
if语句的使用
a.if 通常用于where语句中,通过判断参数决定 执行的筛选条件
test用于参数检查
当if满足条件 会自动删除and
<select id="selectByParams" parameterType="map" resultType="user">
select * from user
<where>
<if test="name != null and name.length()>0" >and name=#{name}</if> #先进行null判断,再对空字符串判断
<where>
</select>
b.在Update更新中使用if
场景:update不能将原来有值 更新成为空或null
set 进行值的修改
<update id="updateByPrimaryKeySelective" parameterType="RecruitmentConfBanner">
UPDATE conf_banner t
<set>
<if test="bannerName != null">
t.banner_name = #{bannerName},
</if>
</set>
where t.banner_id = #{bannerId}
</update>
c.在Insert中使用if
场景:如果传入的值不为空,就传入该值;如果为空,就使用数据库的默认值。
values左右两边都要用if
<insert id="insert">
insert into sys_user(
<if test="userEmail !=null and userEmail != ''">
user_email,
</if>
)
VALUES
(
<if test="userEmail != null and userEmail !=''">
user_email = #{userEmail},
</if>
</insert>
choose用法
场景:实现了if…else
where 1=1 起到永真的作用 返回所有结果
where 1=2 不返回任何结果
<select id="findUserInfoByOneParam" parameterType="Map" resultMap="UserInfoResult">
select * from userinfo
where 1=1
<choose>
<when test="searchBy=='department'">
and department=#{department}
</when>
<when test="searchBy=='position'">
and position=#{position}
</when>
<otherwise>
and 1=2
</otherwise>
</choose>
</select>
where、set、trim用法
- where 如果where有结果返回,会将后面字符串是以AND和OR开头的,会自动将开头的AND/OR其删除
<where>
<if test="name != null and name.length()>0" >and name=#{name}</if> #先进行null判断,再对空字符串判断
<where>
- 如果set有返回结果会将最后一个逗号去掉
<update>
update user
<set>
<if test="name != null and name.length()>0">name = #{name},</if>
<if test="gender != null and gender.length()>0">gender = #{gender},</if>
</set>
where id = #{id}
</update>
- where和set标签的功能都可以用trim标签来实现
where功能的实现
<trim prefix="WHERE" prefixoverride="AND |OR">
<if test="name != null and name.length()>0"> AND name=#{name}</if>
</trim>
set功能的实现
<trim prefix="set" suffixoverride="," suffix=" where id = #{id} ">
<if test="name != null and name.length()>0"> name=#{name} , </if>
</trim>
foreach实现in集合
场景:选取一定范围id内的对象
这里需要接口的参数 为集合 Long[] idArray
<select id="dynamicForeachTest" parameterType="java.util.List" resultType="Blog">
select * from t_blog where id in
<foreach collection="list" index="index" item="item" open="(" separator="," close=")">
#{item}
</foreach>
</select>
bind用法
场景:创建一个变量并将其绑定到上下文,解决切换数据库而导致的语法问题
<!-- List<Employee> getEmpsTestInnerParameter(Employee employee); -->
<select id="getEmpsTestInnerParameter" resultType="com.hand.mybatis.bean.Employee">
<!-- bind:可以将OGNL表达式的值绑定到一个变量中,方便后来引用这个变量的值 -->
<bind name="bindeName" value="'%'+eName+'%'"/> eName是employee中一个属性值
SELECT * FROM emp
<if test="_parameter!=null">
where ename like #{bindeName}
</if>
</select>