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层面,去执行一个逻辑代码

相关推荐
十六年开源服务商43 分钟前
外贸WordPress用户反馈分析与运营维护
运维·服务器·数据库
·云扬·43 分钟前
深入理解MySQL事务:ACID特性、隔离级别与MVCC原理
数据库·mysql·oracle
90的程序爱好者44 分钟前
Kettle多张表数据抽取操作步骤
数据库·数据仓库·数据挖掘
万邦科技Lafite1 小时前
小红书评论数据一键获取,item_reviewAPI接口讲解
大数据·前端·数据库·chrome·电商开放平台
傻啦嘿哟1 小时前
用Pydantic验证和解析配置数据:比手写if更可靠
网络·数据库·oracle
guoketg1 小时前
langchain1.0+RAG检索增强的简易知识库问答系统
数据库
沐雨风栉1 小时前
用 Kavita+cpolar 把数字书房装进口袋
服务器·开发语言·数据库·后端·golang
专注echarts研发20年2 小时前
Qt自定义双击事件实现方案(规避原生双击附带单击问题)
数据库
Linux蓝魔2 小时前
外网同步所有ubuntu源到内网使用
linux·数据库·ubuntu