May 16, 2021 MyBatis
- <select id="select"
- resultType="Blog">
- SELECT * FROM BLOG
- WHERE state = ‘ACTIVE’
- <if test="title != null">
- AND title like #{title}
- </if>
- <if test="name!= null">
- AND name like #{title}
- </if>
- </select>
In a situation like the one above, if there are no conditions behind where, then you need to write the if judgment directly (the beginning is and / or, it will be removed)
- <select id="select"
- resultType="Blog">
- SELECT * FROM BLOG
- <where>
- <if test="title != null">
- AND title like #{title}
- </if>
- <if test="name!= null">
- AND name like #{title}
- </if>
- <where>
- </select>
choose is equivalent to the switch statement in java. otherwise (otherwise)
- <select id="findActiveBlogLike"
- resultType="Blog">
- SELECT * FROM BLOG WHERE state = ‘ACTIVE’
- <choose>
- <when test="title != null">
- AND title like #{title}
- </when>
- <when test="author != null and author.name != null">
- AND author_name like #{author.name}
- </when>
- <otherwise>
- AND featured = 1
- </otherwise>
- </choose>
- </select>
tirm
prefix: Prefixoverride: Remove the first and or or
select * from test
<trim prefix="WHERE" prefixoverride="AND丨OR">
<if test="a!=null and a!=' '">AND a=#{a}<if>
<if test="b!=null and b!=' '">AND a=#{a}<if>
</trim>
The set element is primarily used in update operations, and if the contained statement ends with a comma, the comma is ignored and an error occurs if the set contains empty content.
- <update id="dynamicSetTest" parameterType="Blog">
- update t_blog
- <set>
- <if test="title != null">
- title = #{title},
- </if>
- <if test="content != null">
- content = #{content},
- </if>
- <if test="owner != null">
- owner = #{owner}
- </if>
- </set>
- where id = #{id}
- </update>
Foreach is primarily used in building in conditions
- <select id="dynamicForeachTest" resultType="Blog">
- select * from t_blog where id in
- <foreach collection="list" index="index" item="item" open="(" separator="," close=")">
- #{item}
- </foreach>
- </select>
open separator close
Equivalent to in (? , ? , ? )
What if it's a map?
- <select id="dynamicForeach3Test" resultType="Blog">
- select * from t_blog where title like "%"#{title}"%" and id in
- <foreach collection="ids" index="index" item="item" open="(" separator="," close=")">
- #{item}
- </foreach>
- </select>
Collection corresponds to the map key, like this
- List<Integer> ids = new ArrayList<Integer>();
- ids.add(1);
- ids.add(2);
- ids.add(3);
- ids.add(6);
- ids.add(7);
- ids.add(9);
- Map<String, Object> params = new HashMap<String, Object>();
- params.put("ids", ids);