1 为什么需要动态SQL?
2 动态标签有哪些?
按照官网的分类,MyBatis 的动态标签主要有四类:
- if
- choose (when, otherwise)
- trim (where, set)
- foreach
3 举例说明
if
需要判断的时候,条件写在test中:
<!-- 动态SQL where 和 if --> <select id="selectBlogListIf" parameterType="blog" resultMap="BaseResultMap" > select bid, name, author_id authorId from blog <where> <if test="bid != null"> AND bid = #{
bid} </if> <if test="name != null and name != ''"> AND name LIKE '%${
name}%' </if> <if test="authorId != null"> AND author_id = #{
authorId} </if> </where> </select>
choose (when, otherwise)
需要选择—个条件的时候:
<!-- 动态SQL choose --> <select id="selectBlogListChoose" parameterType="blog" resultMap="BaseResultMap" > select bid, name, author_id authorId from blog <where> <choose> <when test="bid !=null"> bid = #{
bid, jdbcType=INTEGER} </when> <when test="name != null and name != ''"> AND name LIKE CONCAT(CONCAT('%', #{
name, jdbcType=VARCHAR}),'%') </when> <when test="authorId != null "> AND author_id = #{
authorId, jdbcType=INTEGER} </when> <otherwise> </otherwise> </choose> </where> </select>
trim (where, set)
需要去掉where, and、逗号之类的符号的时候:
<!-- 动态SQL set --> <update id="updateByPrimaryKey" parameterType="blog"> update blog <set> <if test="name != null"> name = #{
name,jdbcType=VARCHAR}, </if> <if test="authorId != null"> author_id = #{
authorId,jdbcType=CHAR}, </if> </set> where bid = #{
bid,jdbcType=INTEGER} </update>
用来指定或者去掉前缀或者后缀:
<insert id="insertBlog" parameterType="blog"> insert into blog <trim prefix="(" suffix=")" suffixOverrides=","> <if test="bid != null"> bid, </if> <if test="name != null"> name, </if> <if test="authorId != null"> author_id, </if> </trim> <trim prefix="values (" suffix=")" suffixOverrides=","> <if test="bid != null"> #{
bid,jdbcType=INTEGER}, </if> <if test="name != null"> #{
name,jdbcType=VARCHAR}, <!-- #{
name,jdbcType=VARCHAR,typeHandler=com.gupaoedu.type.MyTypeHandler}, --> </if> <if test="authorId != null"> #{
authorId,jdbcType=INTEGER}, </if> </trim> </insert>
foreach
需要遍历集合的时候:
<!-- foreach 动态SQL 批量删除 --> <delete id="deleteByList" parameterType="java.util.List"> delete from blog where bid in <foreach collection="list" item="item" open="(" separator="," close=")"> #{
item.bid,jdbcType=INTEGER} </foreach> </delete>
发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/206411.html原文链接:https://javaforall.net
