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

相关推荐
增量星球12 分钟前
embedding专题之向量化革命:从关键词到语义检索
数据库·embedding
夕除12 分钟前
redis--008
java·jvm·数据库
烬羽21 分钟前
一个博客系统,为什么要拆成 6 张表?
数据库·mysql
程序员-Benothing23 分钟前
MySQL 中的日志类型有哪些?binlog、redo log 和 undo log 的作用和区别是什么?
数据库·mysql
XuCoder26 分钟前
你写的每条 SQL 都没加过锁,可 MySQL 凭什么不怕两个事务打架?
数据库·后端
2301_8009549936 分钟前
MySQL 数据库基础:数据类型、查询与备份恢复
数据库·mysql·oracle
起名真的太难了38 分钟前
Mysql的数据类型,查询与备份操作
数据库·sql·mysql
程序猿_极客39 分钟前
【免费】分享一套优质的基于Php+Mysql的电子购物网站的设计与实现,校园小卖部系统
数据库·mysql·php·购物商城系统
fīɡЙtīиɡ ℡40 分钟前
LLM/Agent 安全实战核心要点总结
网络·数据库·安全
程序员夏洛41 分钟前
MySQL 中有哪些锁类型?
数据库·mysql