Mybatis实现动态SQL

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

在 MyBatis 之前的版本中,需要花时间了解大量的元素。借助功能强大的基于 OGNL 的表达式,MyBatis 3 替换了之前的大部分元素,大大精简了元素种类,现在要学习的元素种类比原来的一半还要少。
​
if
choose (when, otherwise)
trim (where, set)
foreach

搭建环境:

CREATE TABLE `blog` (
  `id` varchar(50) NOT NULL ,
  `title` varchar(100) NOT NULL ,
  `author` varchar(30) NOT NULL ,
  `create_time` datetime NOT NULL,
  `views` int(30) NOT NULL 
) ENGINE=InnoDB DEFAULT CHARSET=utf8

创建一个基础工程三步骤:

  1. 导包
  2. 编写配置文件
  3. 编写实体类

//使用了lombok注解
@Data
public class Blog {
    private String id;
    private String title;
    private String author;
    private Date createTime;//属性名和字段名不一致
    private int views;
}
  1. 编写实体类对应的mapper接口和xxmapper.xml

IF:

mapper:

//查询blog
List<Blog> getBlogIf(Map map);

mapper.xml

<select id="getBlogIf" parameterType="map" resultType="Blog">
    select * from blog where 1=1
    <if test="title != null">
        and title like "%"#{title}"%"
    </if>
    <if test="author != null">
        and author = #{author}
    </if>
​
</select>

test(测试代码):

@Test
public void getBlogIf(){
    SqlSession sqlsession = MybatisUtils.getSqlsession();
    BlogMapper mapper = sqlsession.getMapper(BlogMapper.class);
    HashMap map = new HashMap();
    map.put("title","mybatis");
    List<Blog> blogIf = mapper.getBlogIf(map);
    for (Blog blog : blogIf) {
        System.out.println(blog);
    }
    sqlsession.close();
}
 

choose (when, otherwise)

<!--choose标签只能选择一个标签-->
<select id="getBlogChoose" parameterType="map" resultType="Blog">
    select * from 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)

where 元素只会在子元素返回任何内容的情况下才插入 “WHERE” 子句。而且,若子句的开头为 “AND” 或 “OR”,where 元素也会将它们去除。

<select id="getBlogIf" parameterType="map" resultType="Blog">
    select * from blog
    <where>
        <if test="title != null">
            title like "%"#{title}"%"
        </if>
        /*where 标签可以智能取出and标签*/
        <if test="author != null">
            and author = #{author}
        </if>
    </where>
​
</select>

set 元素会动态地在行首插入 SET 关键字,并会删掉额外的逗号(这些逗号是在使用条件语句给列赋值时引入的)。

<update id="updateBlog" parameterType="map">
    update blog
    <set>
        <if test="title != null">
            title = #{title},
        </if>
        <if test="author =! null">
            author = #{author},
        </if>
        <if test="views =! null">
            views = #{views}
        </if>
    </set>
    where id = #{id}
</update>

trim:就是设置关于where和set的前后忽略内容:

<trim prefix="WHERE" prefixOverrides="AND |OR ">
  ...
</trim>
<trim prefix="SET" suffixOverrides=",">
  ...
</trim>

forearch:

foreach 元素的功能非常强大,它允许你指定一个集合,声明可以在元素体内使用的集合项(item)和索引(index)变量。它也允许你指定开头与结尾的字符串以及集合项迭代之间的分隔符。

 
<select id="queryBlogForeach" parameterType="map" resultType="Blog">
    select * from blog
    <where>
        <foreach collection="ids" item="id" open="and (" close=")" separator="or">
            id = #{id}
        </foreach>
    </where>
</select>

测试:

@Test
public void queryBlogForeach(){
    SqlSession sqlsession = MybatisUtils.getSqlsession();
    BlogMapper mapper = sqlsession.getMapper(BlogMapper.class);
    HashMap map = new HashMap();
​
    ArrayList<Integer> ids = new ArrayList<>();
    ids.add(1);
    map.put("ids",ids);
    //        map.put("title","mybatis");
    //        map.put("views",100);
    //        map.put("id","1");
    List<Blog> blogs = mapper.queryBlogForeach(map);
    for (Blog blog : blogs) {
        System.out.println(blog);
    }
    sqlsession.close();
}

SQL片段:

将SQL公共部分抽取出来,方便于共用

如:判断是否存在title时、

  • 使用SQL标签提取公共部分(最好只包含简单判断)

<sql id="if-tltle">
    <if test="title != null">
        title = #{title},
    </if>
</sql>
  • 在需要使用的地方使用include标签

<update id="updateBlog" parameterType="map">
    update blog
    <set>
        <include refid="if-tltle"></include>
        <if test="author != null">
            author = #{author},
        </if>
        <if test="views != null">
            views = #{views}
        </if>
    </set>
    where id = #{id}
</update>

动态SQL就是在拼接SQL语句。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值