Mybatis学习笔记七:动态SQL语句的使用

上一章实现了Mybatis与SpringMVC的整合,在本章中将回归Mybatis的功能描述,Mybatis是一个灵活程度很高的框架,他支持动态SQL语句,给开发带来了很大的便利。主要记录几个常用的使用方法,不常用的就用时再翻了。

1、创建一个表BLOG


SET NAMES utf8;
SET FOREIGN_KEY_CHECKS = 0;

-- ----------------------------
--  Table structure for `blog`
-- ----------------------------
DROP TABLE IF EXISTS `blog`;
CREATE TABLE `blog` (
  `id` int(10) NOT NULL AUTO_INCREMENT,
  `title` varchar(255) NOT NULL,
  `content` varchar(255) NOT NULL,
  `owner` varchar(255) NOT NULL,
  `type` varchar(255) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;

-- ----------------------------
--  Records of `blog`
-- ----------------------------
BEGIN;
INSERT INTO `blog` VALUES ('1', 'title1', 'content1', 'owner1', 'type1'), ('2', 'title2', 'content2', 'owner2', 'type2'), ('3', 'title3', 'content3', 'owner3', 'type3');
COMMIT;

SET FOREIGN_KEY_CHECKS = 1;

本章主要使用这个表和其中的数据进行操作。

2、if语句

如代码所示:

<select id="blogIfTest" parameterType="Blog" resultType="Blog">
        SELECT * FROM blog WHERE 1=1
        <if test="title!=null">
            AND title=#{title}
        </if>
        <if test="content!=null">
            AND content=#{content}
        </if>
        <if test="owner!=null">
            AND owner=#{owner}
        </if>
    </select>

与java中的if语句类似,这样做可以动态变更sql语句的长度;

3、Choose语句

<select id="blogChooseTest" parameterType="Blog" resultType="Blog">
        SELECT * FROM blog WHERE 1=1
        <choose>
            <when test="title!=null">
                AND title=#{title}
            </when>

            <otherwise>
                AND owner="owner1"
            </otherwise>
        </choose>
    </select>

Choose语句与switch类似,otherwise与default标签类似。

4、Where语句

<select id="blogWhereTest" parameterType="Blog" resultType="Blog">
        select * from blog
        <where>
            <if test="title != null">
                title = #{title}
            </if>
            <if test="content != null">
                and content = #{content}
            </if>
            <if test="owner != null">
                and owner = #{owner}
            </if>
        </where>
    </select>

where语句用于添加后缀条件。

5、foreach语句

<select id="blogForeachTest" resultMap="blogList">
        select * from blog where id in
        <foreach collection="list" index="index" item="item" open="(" separator="," close=")">
            #{item}
        </foreach>
    </select>

foreach语句一般与in连用,多用在集合中。

6、总结

比较常用的if、where和foreach语句比较重要,需要掌握,其他的需要的时候再看。
未尽之处后期再补,代码下载地址:https://github.com/EdwardEricZhang/MybatisFun

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值