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

相关推荐
子超兄5 分钟前
MVCC机制简介
数据库·mysql
虹科网络安全9 分钟前
艾体宝洞察 | 在 Redis 之上,聊一聊架构思维
数据库·redis·架构
yuguo.im13 分钟前
如何查看 Mysql 版本
数据库·mysql
中年程序员一枚14 分钟前
让postman调用python的开发接口,链接sqlite数据库,让前后联动起来
数据库·python·postman
weixin_4624462317 分钟前
解决MongoDB官网下载过慢问题
数据库·mongodb
青蛙大侠公主24 分钟前
Spring事务
java·数据库·spring
老华带你飞29 分钟前
校务管理|基于springboot 校务管理系统(源码+数据库+文档)
java·数据库·vue.js·spring boot·后端·spring
zzz大王1 小时前
sql 五十题 26-30
数据库·sql
互联网哪些事情2 小时前
服务器防御 SQL 注入
运维·服务器·sql·sql注入主机
小尧嵌入式2 小时前
QT软件开发知识点流程及记事本开发
服务器·开发语言·数据库·c++·qt