MyBatis 的强大特性之一便是它的动态 SQL, 本章介绍动态 SQL
查看本章, 请先阅读 [Mybatis] MyBatis 对表执行 CRUD 操作 (三) https://www.cnblogs.com/h--d/p/10264650.html .
本例表结构
- CREATE TABLE `employee` (
- `id` int(11) NOT NULL AUTO_INCREMENT,
- `last_name` varchar(255) DEFAULT NULL,
- `gender` char(1) DEFAULT NULL,
- `email` varchar(255) DEFAULT NULL
- PRIMARY KEY (`id`)
- ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
- if
示例
1,EmployeeMapper 新增 Sql 如下:
- <!-- if: 判断 -->
- <select id="testConditionIf"
- resultType="com.hd.test.pojo.Employee">
- select id, last_name lastName, gender from employee
- <!--
- test: 判断表达式 (OGNL) OGNL 参照 PPT 或者官方文档.
- c:if test 从参数中取值进行判断 遇见特殊符号应该去写转义字符: &&:
- -->
- where 1 = 1
- <if test="id != null">
- AND id = #{id}
- </if>
- <!-- 表达式中, 字符串使用''单引号引起来 -->
- <if test="lastName != null and lastName.trim() !=''">
- AND last_name = #{lastName}
- </if>
- <!-- ognl 会进行字符串与数字的转换判断 "0"==0 -->
- <if test="gender==0 or gender==1">
- AND gender = #{gender}
- </if>
- <!-- 转义字符: && == && "" == ""-->
- <if test="email != null && lastName!=""">
- AND email = #{email}
- </if>
- </select>
2,EmployeeMapper 接口中, 新增方法
1 public List<Employee> testConditionIf(Employee employee);
3, 测试方法
- @Test
- public void test001() throws IOException {
- InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
- SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
- SqlSession session = sessionFactory.openSession();
- try {
- EmployeeMapper mapper = session.getMapper(EmployeeMapper.class);
- List<Employee> list = mapper.testConditionIf(new Employee(null, "0", null));
- System.out.println(list.size());
- for (Employee employee : list) {
- System.out.println(list);
- }
- } catch (Exception e) {
- e.printStackTrace();
- } finally {
- session.close();
- }
- }
4, 执行结果
choose
有时我们不想应用到所有的条件语句, 而只想从中择其一项. 针对这种情况, MyBatis 提供了 choose 元素, 它有点像 Java 中的 switch 语句.
示例
1,EmployeeMapper 新增 Sql 如下:
- <!-- choose -->
- <select id="testConditionChoose" resultType="com.hd.test.pojo.Employee">
- select id, last_name lastName, gender from employee
- where 1 = 1
- <choose>
- <when test="id != null">
- AND id = #{id}
- </when>
- <when test="lastName != null">
- AND last_name = #{lastName}
- </when>
- <when test="gender != null">
- AND gender = #{gender}
- </when>
- <when test="email != null">
- AND email = #{email}
- </when>
- <otherwise>
- AND 1 = 1
- </otherwise>
- </choose>
- </select>
2,EmployeeMapper 接口中, 新增方法
1 public List<Employee> testConditionChoose(Employee employee);
3, 测试方法
- @Test
- public void test002() throws IOException {
- InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
- SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
- SqlSession session = sessionFactory.openSession();
- try {
- EmployeeMapper mapper = session.getMapper(EmployeeMapper.class);
- List<Employee> list = mapper.testConditionChoose(new Employee(1, null, null, null));
- System.out.println(list.size());
- for (Employee employee : list) {
- System.out.println(list);
- }
- } catch (Exception e) {
- e.printStackTrace();
- } finally {
- session.close();
- }
- }
4, 执行结果
where
- <!-- if + where -->
- <select id="testConditionIfWhere"
- resultType="com.hd.test.pojo.Employee">
- select id, last_name lastName, gender from employee
- <where>
- <if test="id != null">
- AND id = #{id}
- </if>
- <if test="lastName != null and lastName.trim() !=''">
- AND last_name = #{lastName}
- </if>
- <if test="gender==0 or gender==1">
- AND gender = #{gender}
- </if>
- <if test="email != null && lastName!=""">
- AND email = #{email}
- </if>
- </where>
- </select>
- @Test
- public void test003() throws IOException {
- InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
- SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
- SqlSession session = sessionFactory.openSession();
- try {
- EmployeeMapper mapper = session.getMapper(EmployeeMapper.class);
- List<Employee> list = mapper.testConditionIfWhere(new Employee("小红", "1", null));
- System.out.println(list.size());
- for (Employee employee : list) {
- System.out.println(list);
- }
- } catch (Exception e) {
- e.printStackTrace();
- } finally {
- session.close();
- }
- }
- <select id="testConditionIfTrim" resultType="com.hd.test.pojo.Employee">
- select id, last_name lastName, gender from employee
- <!-- 后面多出的 and 或者 or where 标签不能解决
- prefix="": 前缀: trim 标签体中是整个字符串拼串 后的结果. prefix 给拼串后的整个字符串加一个前缀
- prefixOverrides="": 前缀覆盖: 去掉整个字符串前面多余的字符
- suffix="": 后缀 suffix 给拼串后的整个字符串加一个后缀
- suffixOverrides="" 后缀覆盖: 去掉整个字符串后面多余的字符 -->
- <trim prefix="where" prefixOverrides="AND">
- <if test="id != null">
- AND id = #{id}
- </if>
- <if test="lastName != null">
- AND last_name = #{lastName}
- </if>
- <if test="gender != null">
- AND gender = #{gender}
- </if>
- <if test="email != null">
- AND email = #{email}
- </if>
- </trim>
- </select>
- @Test
- public void test004() throws IOException {
- InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
- SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
- SqlSession session = sessionFactory.openSession();
- try {
- EmployeeMapper mapper = session.getMapper(EmployeeMapper.class);
- List<Employee> list = mapper.testConditionIfTrim(new Employee(1, null, null, null));
- System.out.println(list.size());
- for (Employee employee : list) {
- System.out.println(list);
- }
- } catch (Exception e) {
- e.printStackTrace();
- } finally {
- session.close();
- }
- }
- <!-- foreach -->
- <select id="testConditionForeach" resultType="com.hd.test.pojo.Employee">
- select id, last_name lastName, gender from employee
- <!--
- collection: 指定要遍历的集合:
- list 类型的参数会特殊处理封装在 map 中, map 的 key 就叫 list
- item: 将当前遍历出的元素赋值给指定的变量
- separator: 每个元素之间的分隔符
- open: 遍历出所有结果拼接一个开始的字符
- close: 遍历出所有结果拼接一个结束的字符
- index: 索引. 遍历 list 的时候是 index 就是索引, item 就是当前值
- 遍历 map 的时候 index 表示的就是 map 的 key,item 就是 map 的值
- #{变量名} 就能取出变量的值也就是当前遍历出的元素
- -->
- <foreach collection="ids" item="id" separator="," open="where id in (" close=")">
- #{id}
- </foreach>
- </select>
- @Test
- public void test005() throws IOException {
- InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
- SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
- SqlSession session = sessionFactory.openSession();
- try {
- EmployeeMapper mapper = session.getMapper(EmployeeMapper.class);
- List<Employee> list = mapper.testConditionForeach(Arrays.asList(1, 2, 3, 4));
- System.out.println(list.size());
- for (Employee employee : list) {
- System.out.println(list);
- }
- } catch (Exception e) {
- e.printStackTrace();
- } finally {
- session.close();
- }
- }
- <!-- set -->
- <update id="testConditionSet">
- update employee
- <set>
- <if test="lastName != null">
- last_name = #{lastName},
- </if>
- <if test="gender != null">
- gender = #{gender},
- </if>
- <if test="email != null">
- email = #{email},
- </if>
- </set>
- where id = #{id}
- </update>
- @Test
- public void test006() throws IOException {
- InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
- SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
- SqlSession session = sessionFactory.openSession();
- try {
- EmployeeMapper mapper = session.getMapper(EmployeeMapper.class);
- boolean f = mapper.testConditionSet(new Employee(1, "小白", "1", null));
- System.out.println(f);
- session.commit();
- } catch (Exception e) {
- e.printStackTrace();
- } finally {
- session.close();
- }
- }
- <select id="testConditionBind" resultType="Blog">
- <bind name="pattern" value="'%' + keyword + '%'" />
- SELECT * FROM employee WHERE last_name LIKE #{pattern}
- </select>
- sql
- <sql id="selectSql">select id, last_name lastName, gender from employee</sql>
- <select id="testConditionInclude" resultType="com.hd.test.pojo.Employee">
- <include refid="selectSql"></include>
- where id = 1
- </select>
来源: http://www.bubuko.com/infodetail-2935901.html