动态SQL

什么是动态SQL?
动态SQL是指根据不同条件生成不同的SQL语句

IF:

    <select id="getBlogIf" 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>

choose ,when ,otherwise(类似于switch-case):

    <select id="getBlogChoose" resultType="blog" parameterType="map">
        select * from mybatis.blog
        <where>
            <choose>
                <when test="title != null">
                    title=#{title}
                </when>
                <when test="author!=null">
                    author=#{author}
                </when>
                <otherwise>
                views=#{views}
                </otherwise>
            </choose>
        </where>
    </select>

按顺序,when里面哪个存在就用哪个

where标签:
处理“1=1”,and/or,where的问题

set标签:当使用update语句时需要用到set,用set标签可以当在里面使用if标签时去掉多余的逗号,但不会添加逗号

trim标签:

sql片段:
用sql标签写上一段sql语句,在需要引用的地方用include标签引用

 <sql id="if-author">
        <if test="title != null">
            and title=#{title}
        </if>
        <if test="author != null">
            and author=#{author}
        </if>
    </sql>
    <select id="getBlogIf" parameterType="map" resultType="blog">
        select * from mybatis.blog
        <where>
            <include refid="if-author"/>
        </where>

用sql片段可以实现代码的复用;
最好基于单表定义sql片段;不要存在where标签

foreach标签:
属性:
collection:传入一个集合,对其进行遍历
item:每个元素的名称
open:结果以什么开头
close:结尾
seperator:分隔符

    <select id="getBlogForeach" parameterType="map" resultType="blog">
        select * from mybatis.blog
<where>
<foreach collection="ids" index="index" item="id" open="(" close=")" separator="or">
    id=#{id}
</foreach>
</where>
    </select>
    public void getBlogForeach(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
        HashMap hashMap = new HashMap();
        ArrayList<Integer> ids = new ArrayList<>();
        ids.add(1);
        ids.add(2);
        hashMap.put("ids",ids);
        List<Blog> blogs = mapper.getBlogForeach(hashMap);
        for (Blog blog : blogs) {
            System.out.println(blog);
        }
        sqlSession.close();
    }

如上:传入一个"ids"集合,foreach遍历集合的每一个元素,最终实现的sql语句为:

==>  Preparing: select * from mybatis.blog WHERE ( id=? or id=? ) 
==> Parameters: 1(Integer), 2(Integer)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值