芯が強い人になるESTJ-A

# 动态SQL

IT開発 Tags: 无标签 阅读: 295

截屏2021-07-24 20.18.57.jpg

IF

    <select id="queryBlogIF" parameterType="map" resultType="com.xuwen.pojo.Blog">
        select * from koa2weibo.blog
        <where>
            <if test="title != null">
                and title = #{title}
            </if>
            <if test="author !=null">
                and author =#{author}
            </if>
        </where>
    </select>

choose,when,otherwise

    <select id="queryBlogChoose" parameterType="map" resultType="blog">
        select * from koa2weibo.blog
        <where>
            <choose>
                <when test="title != null">
                    title = #{title}
                </when>
                <when test="author != null">
                     and author = #{author}
                </when>
                <otherwise>
                    and views = #{views}
                </otherwise>

            </choose>
        </where>
    </select>

trim(where,set)

    <update id="updateBlog" parameterType="map">
        update koa2weibo.blog
        <set>
            <if test="title !=null">
                title =#{title},
            </if>
            <if test="author != null">
                author = #{author}
            </if>
        </set>
        where id=#{id}
    </update>

BlogMapper

万能的map句

package com.xuwen.dao;

import com.xuwen.pojo.Blog;

import java.util.List;
import java.util.Map;

/**
 * author:xuwen
 * Created on 2021/7/24
 */
public interface BlogMapper {
    //插入数据
    int addBlog(Blog blog);

    //查询博客
    List<Blog> queryBlogIF(Map map);

    //
    List<Blog> queryBlogChoose(Map map);

    //更新博客
    int updateBlog(Map map);



}

SQL代码片段

只用于单表查询
不要存在where标签

    <!--sql片段-->
    <sql id="if-title-author">
        <if test="title != null">
            and title = #{title}
        </if>
        <if test="author !=null">
            and author =#{author}
        </if>
    </sql>

    
    <select id="queryBlogIF" parameterType="map" resultType="com.xuwen.pojo.Blog">
        select * from koa2weibo.blog
        <where>
            <include refid="if-title-author"></include>
        </where>
    </select>