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

相关推荐
猫的玖月7 分钟前
(一)MY SQL概述
数据库·sql
脑子进水养啥鱼?39 分钟前
PostgreSQL .history 文件
数据库·postgresql
倔强的石头_1 小时前
5 个真实案例带你避坑:DolphinDB 实时写入、流订阅与高可用调优
数据库
虹科网络安全1 小时前
艾体宝新闻|Redis 月度更新速览:2026 年 3 月
数据库·redis·缓存
Nturmoils1 小时前
DolphinDB 实时时序数据处理踩坑实录:5 类生产故障排查与优化
数据库
csdn2015_1 小时前
postgresql 拼接字段
数据库
\xin2 小时前
pikachu自编SQL(POST)
java·数据库·sql
2301_815901972 小时前
SQL如何将多行记录聚合成逗号分隔字符串_GROUP_CONCAT技巧
jvm·数据库·python
秋92 小时前
Kingbase下载、安装和使用详解
数据库
zjy277772 小时前
Layui tab选项卡如何动态根据ID值进行程序化切换
jvm·数据库·python