Mybatis.xml文件中写sql语句会用到的标签

x33g5p2x  于2022-06-01 转载在 其他  
字(1.7k)|赞(0)|评价(0)|浏览(793)

1:首先说一下#{}和${}和区别:

(1)#{}:

- mybatis在处理的时候会将#{username} 处理成?,用于参数传递时占位

- 当传入的参数是字符串时,会自动加上’'将传递的值括起来

- mapper接口方法中的参数与xml文件中是按照参数位置索引对应的,不是根据参数的名称,但是建议最好一致。

(2)¥{}:

${}:

- 字符串拼接

mapper接口方法中的参数与xml文件中是按照参数位置索引对应的,不是根据参数的名称,但是建议最好一致。

- mybatis在处理的时候会直接拼接在传递的sql上,不会生成占位的?符号

- 可以用于创建统一的方法,比如对所有表按照id查询。

- select * from ${tableName} where id = #{id} -----> mybatis操作后:select * from student where id = ‘7dsj’

分支结构: 如果只需要一个条件有效,则使用分支结构用法.

  1. <!--
  2. 如果只需要一个条件有效,则使用分支结构用法.
  3. -->
  4. <select id="findChoose" resultType="User">
  5. select * from demo_user
  6. <where>
  7. <choose>
  8. <when test="name !=null">
  9. name = #{name}
  10. </when>
  11. <when test="age !=null">
  12. age = #{age}
  13. </when>
  14. <otherwise>
  15. sex = #{sex}
  16. </otherwise>
  17. </choose>
  18. </where>
  19. </select>

实现用户数据修改, 根据对象中不为null的数据完成修改操作:一般都用到,否则你在修改操作的时候会直接将没有修改的值变为null:

  1. <!--
  2. set标签用法: 去除set条件中多余的,号
  3. -->
  4. <update id="updateSqlSet">
  5. update demo_user
  6. <set>
  7. <if test="name !=null"> name=#{name}, </if>
  8. <if test="age !=null"> age = #{age}, </if>
  9. <if test="sex !=null"> sex = #{sex} </if>
  10. </set>
  11. where id = #{id}
  12. </update>

where-if:

  1. <!-- 动态Sql语句
  2. 核心思想: 自动判断是否为null,
  3. 如果为null,该字段不参与sql
  4. 动态Sql规则:
  5. 1. <if test="写判断条件,可以直接获取属性值"></if>
  6. true: 会拼接 字段条件
  7. false: 不会拼接字段条件
  8. 2. 多余的关键字
  9. 由于动态sql拼接必然会导致多余的and 或者 or
  10. 3. where标签说明 可以去除 where后边多余的and 或者 or
  11. -->
  12. <select id="findSqlWhere" resultType="User">
  13. select * from demo_user
  14. <where>
  15. <if test="id != null"> id = #{id}</if>
  16. <if test="name != null">and name = #{name}</if>
  17. <if test="age != null ">and age = #{age}</if>
  18. <if test="sex != null ">and sex = #{sex}</if>
  19. </where>
  20. </select>

相关文章