在我们传统的开发中我们会通过拼接sql达到数据库的操作。java中的拼接不仅效率低下而且代码很长不易维护。而Mybatis通过代理模式实现SQL语句的组装。简洁易懂。
元素 | 作用 | 备注 |
---|---|---|
if | 判断语句 | 条件分支 |
choose | switch | 多条件分支 |
trim | 去除空字符 | 特殊处理 |
foreach | 集合循环 | 遍历 |
<select id="selectUser">
select id,name,user_sex from User
<where>
<if test="name!=null and name!=‘‘">
and name like concat(‘%‘,concat(#{name},‘%‘))
</if>
</where>
</select>
<select id="selectUser">
select id , name , user_sex from User
<where>
<choose>
<when test="name!=null and name!=‘‘">
and name like concat(‘%‘,concat(#{name},‘%‘))
</when>
<when test="id!=null and id!=‘‘">
and id=#{id}
</when>
<otherwise>
and user_sex=#{userSex}
</otherwise>
</choose>
</where>
</select>
<select id="selectUser">
select id , name , user_sex from User
<trim prefix="where" prefixOverrides="and">
<if test="name!=null and name!=‘‘">
and name like concat(‘%‘,concat(#{name},‘%‘))
</if>
</trim>
</select>
<select id="selectUser">
select * from User where user_sex in
<forearch item="sex" index="index" collection="sexList" open="(" close="}" separator=",">
#{sex}
</forearch>
</select>
<select id="selectUser">
<bind name="pattern" value="‘%‘+_parameter+‘%‘"/>
select id , name , user_sex from User
where name like #{pattern}
</select>
原文:https://www.cnblogs.com/zhangxinhua/p/13029427.html