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

相关推荐
人间打气筒(Ada)17 分钟前
MySQL主从架构
服务器·数据库·mysql
leegong2311119 分钟前
学习PostgreSQL专家认证
数据库·学习·postgresql
喝醉酒的小白20 分钟前
PostgreSQL:更新字段慢
数据库·postgresql
敲敲敲-敲代码22 分钟前
【SQL实验】触发器
数据库·笔记·sql
和道一文字yyds24 分钟前
MySQL 中的索引数量是否越多越好?为什么?如何使用 MySQL 的 EXPLAIN 语句进行查询分析?MySQL 中如何进行 SQL 调优?
数据库·sql·mysql
落笔画忧愁e1 小时前
FastGPT快速将消息发送至飞书
服务器·数据库·飞书
Σίσυφος19001 小时前
halcon 条形码、二维码识别、opencv识别
前端·数据库
小刘|2 小时前
深入理解 SQL 注入漏洞及解决方案
数据库·sql
数巨小码人2 小时前
QT SQL框架及QSqlDatabase类
jvm·sql·qt
天上掉下来个程小白3 小时前
案例-14.文件上传-简介
数据库·spring boot·后端·mybatis·状态模式