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

相关推荐
小叶子来了啊20 分钟前
信息系统运行管理员:临阵磨枪版
运维·服务器·数据库
数据库幼崽44 分钟前
MySQL 8.0 OCP 1Z0-908 131-140题
数据库·mysql·ocp
北漂老男孩1 小时前
主流数据库运维故障排查卡片式速查表与视觉图谱
运维·数据库
源码云商1 小时前
基于SpringBoot的校园周边美食探索及分享平台【附源码+数据库+文档下载】
数据库·spring boot·美食
爱编程的小新☆1 小时前
【MySQL】数据库三大范式
数据库·mysql
随心............1 小时前
MySQL的触发器
数据库·mysql
GUIQU.2 小时前
【MySQL】项目实践
数据库·mysql·项目实践
XINGTECODE3 小时前
海盗王3.0的数据库3合1并库处理方案
数据库·海盗王
tebukaopu1483 小时前
官方 Elasticsearch SQL NLPChina Elasticsearch SQL
大数据·sql·elasticsearch