文章目录
1、综述
在Mapper配置文件中,有时候需要根据一些查询条件来选择不同的SQL语句,或者将一些使用频率极高的SQL语句单独配置,在需要的地方引用。MyBatis提供了一种可以根据条件动态配置SQL语句,以及单独配置SQL语句块的机制。动态SQL,即通过MyBatis提供的各种标签对条件作出判断以实现动态拼接SQL语句。这里的条件判断使用的表达式为OGNL表达式。
2、测试环境搭建
2.1 创建数据库表
在之前测试使用的mybatis数据库中创建student表,创建表的SQL语句及添加测试数据如下:
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for `student`
-- ----------------------------
DROP TABLE IF EXISTS `student`;
CREATE TABLE `student` (
`id` int(5) NOT NULL auto_increment,
`name` varchar(20) default NULL,
`age` int(3) default NULL,
`score` double default NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of student
-- ----------------------------
INSERT INTO `student` VALUES ('1', '张三', '23', '93.5');
INSERT INTO `student` VALUES ('2', '李四', '24', '94.5');
INSERT INTO `student` VALUES ('3', '王五', '25', '92.5');
2.2 定义实体类
在com.ccff.mybatis.model下定义Student实体类,具体代码如下所示:
package com.ccff.mybatis.model;
public class Student {
private int id;
private String name;
private int age;
private double score;
public Student() {
}
public Student(String name, int age, double score) {
this.name = name;
this.age = age;
this.score = score;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public double getScore() {
return score;
}
public void setScore(double score) {
this.score = score;
}
@Override
public String toString() {
return "Student{" +
"id=" + id +
", name='" + name + '\'' +
", age=" + age +
", score=" + score +
'}';
}
}
2.3 定义接口DAO
在com.ccff.mybatis.dao下定义接口IStudentDao,代码如下:
package com.ccff.mybatis.dao;
import com.ccff.mybatis.model.Student;
import java.util.List;
public interface IStudentDao {
//用于测试if标签
List<Student> selectStudentsIf(Student student);
//用于测试where标签
List<Student> selectStudentsWhere(Student student);
//用于测试choose标签
List<Student> selectStudentsChoose(Student student);
//用于测试foreach标签
List<Student> selectStudentsForeachArray(Object[] studentIds);
List<Student> selectStudentsForeachList(List<Integer> studentIds);
List<Student> selectStudentsForeachList2(List<Student> students);
//用于测试sql标签
List<Student> selectStudentsBySQLFragment(List<