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

相关推荐
smilejingwei13 分钟前
数据分析编程第二步: 最简单的数据分析尝试
数据库·算法·数据分析·esprocspl
bing.shao1 小时前
gRPC 选型 etcd 的核心优势分析
数据库·微服务·云原生·golang·etcd
TDengine (老段)2 小时前
TDengine IDMP 应用场景:微电网监控
大数据·数据库·物联网·ai·时序数据库·tdengine·涛思数据
不叫猫先生2 小时前
Amazon Lambda:无服务器时代的计算革命,解锁多样化应用场景
服务器·数据库·人工智能·amazon lambda
秋天枫叶353 小时前
【AI应用】修改向量数据库Milvus默认密码
运维·服务器·数据库·ubuntu·milvus·milvus_cli
l1t3 小时前
分析xml标签属性和压缩级别对xlsx文件读取解析的影响
xml·开发语言·python·sql·duckdb
王伯爵3 小时前
go语言中的select的用法和使用场景
开发语言·数据库·golang
凯子坚持 c3 小时前
Redis 数据类型:List 列表的深度解析与应用
数据库·redis·list
DarkAthena4 小时前
【GaussDB】使用gdb定位GaussDB编译package报错
数据库·gaussdb
DONG9134 小时前
Redis内存架构解析与性能优化实战
数据库·redis·sql·database