您当前的位置: 首页 > 慢生活 > 程序人生 网站首页程序人生
02-mybatis映射文件深入-动态sql-if
发布时间:2025-01-30 14:20:25编辑:雪饮阅读()
-
其实前番中在UserMapper.xml中编写的select查询标签写的太固定条件了
<!--查询操作-->
<select id="findByCondition" parameterType="user" resultType="user">
select * from user where id=#{id} and username=#{username} and password=#{password}
</select>
像是这种固定条件的查询并不太方便。
这里有一种动态方式更好
<!--查询操作-->
<select id="findByCondition" parameterType="user" resultType="user">
select * from user
<where>
<if test="id!=0">
and id=#{id}
</if>
<if test="username!=null">
and username=#{username}
</if>
<if test="password!=null">
and password=#{password}
</if>
</where>
</select>
这里的where标签相当于1=1的条件占位,防止例如下面的if条件达成后,但是默认又没有其它固化where条件,导致直接and,也就是and左侧没有条件的情况,这种情况在mysql中查询语句是不合法的sql语句。
关键字词:mybatis,动态,sql,if