9、SpringBoot+Mybatis整合------动态sql

开发工具:STS

前言:

mybatis框架中最具特色的便是sql语句中的自定义,而动态sql的使用又使整个框架更加灵活。

动态sql中的语法:

where标签

if标签

trim标签

set标签

switch\when标签

foreach标签


一、搭建项目

1.创建用户表:

    

2.添加实体:   

 1 package com.xm.pojo;
 2 /**
 3  * 用户实体
 4  * @author xm
 5  *
 6  */
 7 public class User {
 8
 9     private int id;
10     private String name;
11     private String username;
12     private int age;
13     private String phone;
14     private String email;
15     //无参构造函数必须有,ORM框架调用的就是无参构造函数
16     public User() {
17
18     }
19     public User(int id, String name, String username, int age, String phone, String email) {
20         super();
21         this.id = id;
22         this.name = name;
23         this.username = username;
24         this.age = age;
25         this.phone = phone;
26         this.email = email;
27     }
28     public int getId() {
29         return id;
30     }
31     public void setId(int id) {
32         this.id = id;
33     }
34     public String getName() {
35         return name;
36     }
37     public void setName(String name) {
38         this.name = name;
39     }
40     public String getUsername() {
41         return username;
42     }
43     public void setUsername(String username) {
44         this.username = username;
45     }
46     public int getAge() {
47         return age;
48     }
49     public void setAge(int age) {
50         this.age = age;
51     }
52     public String getPhone() {
53         return phone;
54     }
55     public void setPhone(String phone) {
56         this.phone = phone;
57     }
58     public String getEmail() {
59         return email;
60     }
61     public void setEmail(String email) {
62         this.email = email;
63     }
64
65     @Override
66     public String toString() {
67         return "User [id=" + id + ", name=" + name + ", username=" + username + ", age=" + age + ", phone=" + phone
68                 + ", email=" + email + "]";
69     }
70
71
72
73
74
75 }

User.java

3.添加mapper接口:

 1 package com.xm.mapper;
 2
 3 /**
 4  * 用户mapper接口
 5  * @author xm
 6  *
 7  */
 8 public interface UserMapper {
 9
10 }

UserMapper.java

4.添加mapper映射:

1 <?xml version="1.0" encoding="UTF-8" ?>
2 <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
3 <!--用户mapper关系映射  -->
4 <mapper namespace="com.xm.mapper.UserMapper">
5
6 </mapper>

UserMapper.xml

5.添加测试类:

 1 package com.xm;
 2
 3
 4 import org.junit.runner.RunWith;
 5 import org.springframework.beans.factory.annotation.Autowired;
 6 import org.springframework.boot.test.context.SpringBootTest;
 7 import org.springframework.test.context.junit4.SpringRunner;
 8
 9 import com.xm.mapper.UserMapper;
10
11 @RunWith(SpringRunner.class)
12 @SpringBootTest
13 public class UserTest {
14
15     @Autowired
16     private UserMapper userMapper;
17
18
19 }

UserText.java

二、动态sql

1.if标签的使用 

(1)添加mapper接口:

1 /**
2      * 根据条件查出学生
3      * @param user
4      * @return
5      */
6     public List<User> getUser(User user);

(2)添加mapper映射:

1 <select id="getUser" resultType="user">
2 select * from user where 1=1
3 <if test="id != null">and id=#{id} </if>
4 <if test="age != null">and age=#{age} </if>
5 <if test="name != null">and name=#{name}</if>
6 </select>

(3)添加测试:

 1 @Autowired
 2     private UserMapper userMapper;
 3
 4     @Test
 5     public void getUserTest() {
 6         User user = new User(null , "小明" , null , 12 , null , null);
 7         List<User> users = userMapper.getUser(user);
 8         System.out.println(users);
 9
10     }

(4)测试结果:

(5)思考:

where 1=1 在这里的作用是什么呢?可以不用它吗?

2.where标签的使用

(1)更改mapper映射:

1 <select id="getUser" resultType="user">
2 select * from user
3 <where>
4 <if test="id != null">and id=#{id} </if>
5 <if test="age != null">and age=#{age} </if>
6 <if test="name != null">and name=#{name}</if>
7 </where>
8 </select>

(2)测试结果:

(3)思考:

and id=#{id} 换成 id=#{id} and 会怎样?

3.trim标签的使用

(1)更改mapper映射:

1 <select id="getUser" resultType="user">
2 select * from user
3 <trim prefix="where" suffixOverrides="and">
4 <if test="id != null">id=#{id} and</if>
5 <if test="age != null">age=#{age} and</if>
6 <if test="name != null">name=#{name} and</if>
7 </trim>
8 </select>

(2)测试结果:

(3)分析:

trim标签下的四个属性:

prefix:在标签开始添加上该字符串

suffixOverrides:在标签末尾去除上该字符串

suffix:在标签末尾添加上该字符串

prefixOverrides:在标签开始去除上该字符串

4.set标签的使用

(1)描述需求:

用在update语句中,如果字段参数不为null,则修改此参数

(2)添加mapper接口:

1 /**
2      * 根据id修改所有非空字段
3      * @param user
4      */
5     public void updateUserById(User user);

(3)添加mapper映射:

 1 <update id="updateUserById">
 2 update user
 3 <set>
 4 <if test="name != null">name=#{name},</if>
 5 <if test="age != null">age=#{age},</if>
 6 <if test="username != null">username=#{username},</if>
 7 <if test="email != null">email=#{email},</if>
 8 <if test="phone != null">phone=#{phone}</if>
 9 </set>
10 <where>
11 id=#{id}
12 </where>
13 </update>

(4)添加测试方法:

1 @Test
2     public void updateUserTest() {
3
4         User user = new User(1, null, null, null, "12545564454", "[email protected]");
5         userMapper.updateUserById(user);
6
7     }

(5)测试结果

5.switch\when标签的使用

(1)描述需求:

满足id!=null查询id,

否则,看满足age否,

接着,看name是否满足,

最后,按age>10查询

(2)更改mapper映射:

1 <select id="getUser" resultType="user">
2 select * from user where
3 <choose>
4 <when test="id != null">id=#{id} </when>
5 <when test="age != null">age=#{age}</when>
6 <when test="name != null">name=#{name} </when>
7 <otherwise>age>10</otherwise>
8 </choose>
9 </select>

(3)测试结果:

6.foreach标签的使用

(1)需求描述:

查出多个id的user

(2)添加mapper接口:

1     /**
2      * 根据id批量查询
3      * @param ids
4      * @return
5      */
6     public List<User> listById(List<Integer> ids);

(3)添加mapper映射:

1 <select id="listById" resultType="user" parameterType="list">
2 select * from user where id in
3 <foreach collection="list" item="id" separator=","  open="("  close=")">
4 #{id}
5 </foreach>
6 </select>

(4)添加测试用例:

1 @Test
2     public void listTest() {
3
4         List<User> users = userMapper.listById(Arrays.asList(1));
5         System.out.println(users);
6
7     }

(5)分析:

foreach标签下的所有属性:

collection:获取的集合名,如果是list集合,springboot会把它的key值默认封装为list

item:遍历的单个属性值

separator:拼接隔离的字符串

open:在循环的开始拼接的字符串

close:在循环的结束拼接的字符串

index:索引,在map中作为key



                                                                                2018-07-04

原文地址:https://www.cnblogs.com/TimerHotel/p/springboot_matatis_09.html

时间: 2024-08-28 22:45:37

9、SpringBoot+Mybatis整合------动态sql的相关文章

一分钟带你了解下MyBatis的动态SQL!

MyBatis的强大特性之一便是它的动态SQL,以前拼接的时候需要注意的空格.列表最后的逗号等,现在都可以不用手动处理了,MyBatis采用功能强大的基于OGNL的表达式来实现,下面主要介绍下. 一.if标签 if是最常用的判断语句,主要用于实现某些简单的条件选择.基本使用示例如下: <select id="queryAllUsersByName" resultType="com.example.springboot.mybatisxml.entity.User&quo

MyBatis的动态SQL详解

MyBatis的动态SQL是基于OGNL表达式的,它可以帮助我们方便的在SQL语句中实现某些逻辑,本文详解mybatis的动态sql,需要的朋友可以参考下 MyBatis 的一个强大的特性之一通常是它的动态 SQL 能力.如果你有使用 JDBC 或其他 相似框架的经验,你就明白条件地串联 SQL 字符串在一起是多么的痛苦,确保不能忘了空 格或在列表的最后省略逗号.动态 SQL 可以彻底处理这种痛苦. 通常使用动态SQL不可能是独立的一部分,MyBatis当然使用一种强大的动态SQL语言来改进这种

Mybatis的动态Sql

基础部分可以查看我的另一篇博客:http://blog.csdn.net/elim168/article/details/40622491 MyBatis的动态SQL是基于OGNL表达式的,它可以帮助我们方便的在SQL语句中实现某些逻辑. MyBatis中用于实现动态SQL的元素主要有: if choose(when,otherwise) trim where set foreach if就是简单的条件判断,利用if语句我们可以实现某些简单的条件选择.先来看如下一个例子: Xml代码 <sele

mybatis 使用动态SQL

RoleMapper.java public interface RoleMapper { public void add(Role role); public void update(Role role); public void delete(Role role); public List<Role> getRoleList(Role role); } RoleMapper.xml <?xml version="1.0" encoding="UTF-8&

MyBatis中动态SQL语句完成多条件查询

http://blog.csdn.net/yanggaosheng/article/details/46685565 MyBatis中动态SQL语句完成多条件查询 <select id="queryEmp"  resultType="cn.test.entity.Emp"> select * from emp where 1=1 <if test="deptNo!=null"> and deptno=#{deptNO} &

MyBatis 构造动态 SQL 语句

以前看过一个本书叫<深入浅出 MFC >,台湾 C++ 大师写的一本书.在该书中写道这样一句话,"勿在浮沙筑高台",这句话写的的确对啊.编程很多语言虽然相同,但是真正做还是需要认真的学习,如果只是想着按想像着来,真的是会走很多弯路,浪费很多时间. 无法使用 not in 在项目中需要使用到 not in ,想着不是很复杂,但是这个问题困扰了我个把小时,很是郁闷.自己拼接好了字符串,字符串的内容是 not in 中的各个 id 值.通过 not in 来进行 update 的

MyBatis探究-----动态SQL详解

1.if标签 接口中方法:public List<Employee> getEmpsByEmpProperties(Employee employee); XML中:where 1=1必不可少 <select id="getEmpsByEmpProperties" resultType="com.mybatis.entity.Employee"> select * from t_employee where 1=1 <if test=&

Mybatis系列---动态SQL

问题: 什么是动态SQL? 动态SQL有什么作用? 传统的使用JDBC的方法,相信大家在组合复杂的的SQL语句的时候,需要去拼接,稍不注意哪怕少了个空格,都会导致错误.Mybatis的动态SQL功能正是为了解决这种问题, 其通过 if, choose, when, otherwise, trim, where, set, foreach,可组合成非常灵活的SQL语句,从而提高开发人员的效率. 下述可知道这四个操作节点中的子节点都是差不多是一样的,insert和update中多了一个selectK

Mybatis的动态sql拼接语句

Mybatis的动态sql拼接语句 1.主配置文件SqlMapConfig.xml  <?xml version="1.0" encoding="utf-8" ?> <!DOCTYPE configuration         PUBLIC "-//mybatis.org//DTD Config 3.0//EN"         "http://mybatis.org/dtd/mybatis-3-config.dtd