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

相关推荐
gsfl1 小时前
Redis分布式锁
数据库·redis·分布式
Li zlun2 小时前
MySQL 配置管理与日志系统完全指南:从基础到高级优化
数据库·mysql
勇者无畏4042 小时前
MySQL 中一条 SQL 语句的执行流程
sql·mysql·缓存
wzg20162 小时前
vscode 配置使用pyqt5
开发语言·数据库·qt
老朋友此林3 小时前
MongoDB GEO 项目场景 ms-scope 实战
java·数据库·spring boot·mongodb
极限实验室4 小时前
如何使用 INFINI Gateway 对比 ES 索引数据
数据库
Raymond运维5 小时前
MySQL包安装 -- RHEL系列(离线RPM包安装MySQL)
linux·运维·数据库·mysql
养生技术人6 小时前
Oracle OCP认证考试题目详解082系列第45题
运维·数据库·sql·oracle·开闭原则·ocp
奥尔特星云大使7 小时前
mysql主从配置(保姆级)
数据库·mysql·主从复制
BD_Marathon7 小时前
【MySQL】SQL的分类
数据库·sql·mysql