Dynamic SQL
What is the soul of mybatis? The soul of mybatis is dynamic SQL!
if tag
在映射配置文件中这样写
<select id="findUserByCondition" resultType="com.yixuexi.entity.User" parameterType="com.yixuexi.entity.User">
<!-- 使用if标签 where 1=1不能省略 -->
select * from user where 1 = 1
<if test="name != null">
and name = #{name}
</if>
</select>
- The above if means, if the name of the user object is not empty, then put together and name = #{name}
- The if tag is and or or
- If there are multiple conditions, multiple if tags can be assembled
- The name of test is the name attribute of the user object.
Multiple if tags
select * from user where 1 = 1
<if test="name != null">
and name = #{name}
</if>
<if test="password != null">
and password = #{password}
</if>
Precautions:
- When using the if tag alone, you must add where 1=1
- Multiple if will be executed
where tag
- Use the where tag to omit where1 = 1
- Is to wrap a where tag outside the if tag
<select id="findUserByCondition" resultType="com.yixuexi.entity.User" parameterType="com.yixuexi.entity.User">
select * from user
<where>
<if test="name != null">
and name = #{name}
</if>
<if test="password != null">
and password = #{password}
</if>
</where>
</select>
It's very simple, just add a layer of where tag
foreach tags
<select id="findUserByIds" parameterType="com.yixuexi.entity.QueryVoIds" resultType="com.yixuexi.entity.User">
select * from user
<where> <!--添加了where之后 就不用再手写 where 1=1 -->
<!--如果这个对象里面的list集合不是null,并且 list集合的个数大于0个 则遍历 -->
<if test="list != null and list.size > 0">
<foreach collection="list" open="and id in(" close=")" item="id" separator=",">
#{id}
</foreach>
</if>
</where>
</select>
Detailed label content:
- collection:遍历哪个集合,集合名称
- open:开头添加什么 添加 and id in(
} open哪里加and是因为 where标签会帮你加 where 1=1 不加and不行
- close:在结尾添加什么 添加 )
- item:(起个名)把遍历出来的每一项添加到 open和close之间,用,进行分割
- separator:用什么进行分割
- #{id}:item起的什么名字 这里就用什么名字
- 最后拼装出来的sql: select * from user wherer 1 = 1 and id in (1,2,3,4,5)
Next article update: mybatis multi-table query, one-to-one query