Mybatis——动态SQL常用标签

IF

配置:

java 复制代码
public interface BlogMapper {

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

}
XML 复制代码
    <select id="queryBlogIF" parameterType="map" resultType="blog">
        select * from mybatis.blog where 1=1
        <if test="title != null">
            and title = #{title}
        </if>
        <if test="author != null">
            and author = #{author}
        </if>
    </select>

测试:

java 复制代码
    @Test
    public void queryBlogIF(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
        HashMap map = new HashMap();

        map.put("title","学好Mybatis");

        List<Blog> blogs = mapper.queryBlogIF(map);
        for (Blog blog : blogs) {
            System.out.println(blog);
        }
        sqlSession.close();
    }

choose、when、otherwise

XML 复制代码
    <select id="queryBlogChoose" parameterType="map" resultType="blog">
        select * from mybatis.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

XML 复制代码
    <select id="queryBlogIF" parameterType="map" resultType="blog">
        select * from mybatis.blog
        <where>
            <if test="title != null">
                title = #{title}
            </if>
            <if test="author != null">
                and author = #{author}
            </if>
        </where>
    </select>
XML 复制代码
    <update id="updateBlog" parameterType="map">
        update mybatis.blog
        <set>
            <if test="title != null">
                title = #{title},
            </if>
            <if test="author != null">
                author = #{author]
            </if>
        </set>
        where id = #{id}
    </update>

所谓的动态SQL,本质还是SQL语句,只是我们可以在SQL层面,去执行一个逻辑代码

相关推荐
白熊--π4 分钟前
读懂 Meta API 限流:从范围判断到工程优化
大数据·数据库·meta·facebook
Java爱好狂.6 分钟前
Java小白如何三天速通redis?
java·数据库·redis·架构师·分布式锁·java面试·java程序员
菜鸟上路_lbz8 分钟前
金仓数据库V9自增id报错
数据库
Novproxy_Z18 分钟前
账号批量封禁复盘:从日志定位是 IP 关联还是行为指纹关联
网络·数据库·tcp/ip
我喜欢就喜欢24 分钟前
IT疑难杂症诊疗室:从现象到根因的系统排查指南
数据库
其实防守也摸鱼33 分钟前
Codex 下载与本地部署实战指南
linux·服务器·前端·数据库·算法·ai
2603_9547083141 分钟前
如何进一步优化微能网协调控制箱的架构优势
大数据·数据库·人工智能·分布式·架构
瑶山1 小时前
stable-diffusion.cpp 参数全集整理(sd-cli.exe / sd-server.exe)
java·数据库·stable diffusion·参数全集
Pocker_Spades_A1 小时前
一文读懂时序数据库:2026 主流产品全景与六大场景选型(1)
数据库·时序数据库
oradh1 小时前
Oracle 物化视图维护总结(原理+用途+案例)
数据库·oracle