**什么是动态SQL:**动态SQL就是指根据不同的条件生成不同的SQL语句。
动态SQL元素和JSTL或基于类似XML的文本处理器相似。在mybatis之前的版本中,有很多的元素需要花时间的了解。mybatis3大大精简了元素种类,现在只需学习原来一半的元素便可。mybatis采用功能强大的基于OGNL的表达式来淘汰其他大部分元素。
if
choose(when otherwise)
trim(where set)
foreach
搭建环境
CREATE TABLE `blog`(
`id` VARCHAR(50) NOT NULL COMMENT '博客ID',
`title` VARCHAR(100) NOT NULL COMMENT '博客标题',
`auther` VARCHAR(30) NOT NULL COMMENT '博客作者',
`creat_time` DATETIME NOT NULL COMMENT '创建时间',
`views` INT(30) NOT NULL COMMENT '浏览量'
)ENGINE=INNODB DEFAULT CHARSET=utf8
创建基础工程
- 导包;
- 编写配置文件;
- 编写实体类;
public class blog {
// 博客ID
private long id;
// 博客名
private String title;
// 博客作者
private String auther;
// 创建时间
private Date creatTime;
//
private int views;
}
- 编写实体类对应的mapper接口和mapper.xml文件;
IF
<select id="QueryBlogIF" resultType="com.xiaoshui.entity.Blog">
select * from mybatis.blog
<if test="title != null">
and title = #{title}
</if>
<if test="auther != null">
and auther = #{auther}
</if>
</select>
where
<select id="selectBlogWhere" resultType="com.xiaoshui.entity.Blog" parameterType="map">
select * from mybatis.blog
<where>
<if test="title != null">
and title = #{title}
</if>
<if test="auther != null">
and auther = #{auther}
</if>
</where>
</select>