上一章实现了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