动态SQL
动态SQL
介绍
什么是动态sql:**在我的理解,动态SQL就是根据不同的环境,生成不同的sql语句**
官网描述
MyBatis 的强大特性之一便是它的动态 SQL。如果你有使用 JDBC 或其它类似框架的经验,你就能体会到根据不同条件拼接 SQL 语句的痛苦。例如拼接时要确保不能忘记添加必要的空格,还要注意去掉列表最后一个列名的逗号。利用动态 SQL 这一特性可以彻底摆脱这种痛苦。
虽然在以前使用动态 SQL 并非一件易事,但正是 MyBatis 提供了可以被用在任意 SQL 映射语句中的强大的动态 SQL 语言得以改进这种情形。
动态 SQL 元素和 JSTL 或基于类似 XML 的文本处理器相似。在 MyBatis 之前的版本中,有很多元素需要花时间了解。MyBatis 3 大大精简了元素种类,现在只需学习原来一半的元素便可。MyBatis 采用功能强大的基于 OGNL 的表达式来淘汰其它大部分元素。
<标签>
- if
- choose (when, otherwise)
- trim (where, set)
- foreach
搭建环境
新建一个数据库表:blog
字段: id, title, author, createtime, views
CREATE TABLE 'blog'(
'id' varchar(50) NOT NULL COMMENT '博客id',
'title' varchar(100) NOTNULL COMMENT '博客标题',
'author' varchar(100) NOT NULL COMMENT '博客作者'
'createtime' datetime NOT NULL COMMENT '创建时间',
'views' varchar(50) NOT NULL COMMENT '浏览量'
)ENGINE=lnnoDB DEFAULT CHARSET=utf8
1. 创建Mybatis基础工程
- IDutil工具类
2. IDutil工具类
public class IDUtils {
public static String getId(){
//UUID通用唯一标识符
return UUID.randomUUID().toString().replaceAll("-","");
}
}
3. 实体类的编写
public class Blog {
private String id;
private String title;
private String author;
private Date createtime;
private int views;
public Blog() {
}
public Blog(String id, String title, String author, Date createtime, int views) {
this.id = id;
this.title = title;
this.author = author;
this.createtime = createtime;
this.views = views;
}
@Override
public String toString() {
return "Blog{" +
"id='" + id + '\'' +
", title='" + title + '\'' +
", author='" + author + '\'' +
", createtime=" + createtime +
", views=" + views +
'}';
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public Date getCreatetime() {
return createtime;
}
public void setCreatetime(Date createtime) {
this.createtime = createtime;
}
public int getViews() {
return views;
}
public void setViews(int views) {
this.views = views;
}
}
4. 编写Mapper接口,xml文件
Mapper接口