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

相关推荐
TechWJ6 分钟前
没有公网 IP 也想远程连 PostgreSQL?从本地数据库到固定 TCP 地址完整配置
大数据·数据库·网络安全·postgresql·内网穿透
得物技术1 小时前
指标平台:从语义底座到智能消费的实践路径|得物技术
数据库·人工智能·ai编程
StarRocks_labs1 小时前
当大模型调用进入执行引擎:StarRocks AI Function 全新能力解析
数据库·starrocks·sql·ai·pipeline·数据处理·join
TDengine (老段)1 小时前
TDengine 常见问题 TOP4
数据库·物联网·时序数据库·tdengine·涛思数据·升级·tdengine 问题
小蒜学长1 小时前
基于RFID技术的仓储管理系统设计(代码+数据库+LW)
java·数据库·spring boot·后端·rfid技术·仓储管理
梦影_1 小时前
Langchain简单快速上手教程(五)——聊天模型之流式传输
java·数据库·人工智能·python·langchain
润乾软件2 小时前
SQLazy:找出含 5 个以上连续字母表顺序字母的字符串
sql·sqlazy
数据狐(Datafox)2 小时前
1688商品列表API接口解析(附 JSON 样例)
java·开发语言·数据库·爬虫·json
adinnet20262 小时前
客服与工单:响应时长与满意度问数
数据库·人工智能
文人sec3 小时前
MYSQL:insert...select:为什么锁源表的所有行和间隙?怎么最快地复制一张表?
数据库·python·mysql