【Mybatis学习笔记】—— 【四】动态SQL

需要更好的阅读的体验请移步 👉 小牛肉的个人博客 👈



动态 SQL是MyBatis强大特性之一。极大的简化我们拼装 SQL的操作。
动态 SQL 元素和使用 JSTL 或其他类似基于 XML 的文本处 理器相似。
MyBatis 采用功能强大的基于 OGNL 的表达式来简化操作。

  • if 判断
  • choose (when, otherwise) 分支选择
  • trim (where, set) 字符串截取
  • foreach 遍历集合

1. if 判断 & OGNL 判断表达式

//携带了哪个字段查询条件就带上这个字段的值
public List<Employee> getEmpsByConditionIf(Employee employee);

查询员工,要求:携带了哪个字段查询条件就带上这个字段的值

	 <!-- public List<Employee> getEmpsByConditionIf(Employee employee); -->
	 <select id="getEmpsByConditionIf" resultType="com.smallbeef.mybatis.bean.Employee">
	 	select * from tbl_employee where
		 	<!-- test:判断表达式(OGNL)
		 	从参数中取值进行判断
		 	-->
		 	<if test="id!=null">
		 		id=#{id}
		 	</if>
		 	<if test="lastName!=null and lastName!=''">
		 		and last_name like #{lastName}
		 	</if>
		 	<if test="email!=null and email.trim()!=''">
		 		and email=#{email}
		 	</if> 
		 	<!-- ognl会进行字符串与数字的转换判断  "0"==0 -->
		 	<if test="gender==0 or gender==1">
		 	 	and gender=#{gender}
		 	</if>
	 </select>

如果查询字段email为空

Employee employee = new Employee(1, "Admin", null, 1);
List<Employee> emps = mapper.getEmpsByConditionIf(employee );

则 查询语句为

select * from tbl_employee where id = ? and last_name = ? and gender = ?

2. where 查询条件

上述写法我们可以看见一个问题,如果 id=null,那么查询语句就变成

select * from tbl_employee where and last_name = ? and gender = ?

语法出错,and被强行拼接
解决方法有两种:

  • selet * from table_name 后面加上 where 1 = 1,并在所有的条件语句都加上and前缀
    则如果id = null,那么查询语句任然成立
	 <!-- public List<Employee> getEmpsByConditionIf(Employee employee); -->
	 <select id="getEmpsByConditionIf" resultType="com.smallbeef.mybatis.bean.Employee">
	 	select * from tbl_employee where 1 = 1
		 	<if test="id!=null">
		 		and id=#{id}
		 	</if>
		 	<if test="lastName!=null and lastName!=''">
		 		and last_name like #{lastName}
		 	</if>
		 	<if test="email!=null and email.trim()!=''">
		 		and email=#{email}
		 	</if> 
		 	<!-- ognl会进行字符串与数字的转换判断  "0"==0 -->
		 	<if test="gender==0 or gender==1">
		 	 	and gender=#{gender}
		 	</if>
	 </select>
select * from tbl_employee where 1 = 1 and last_name = ? and gender = ?
  • 将 if 判断语句全都写在 where 标签中
<select id="getEmpsByConditionIf" resultType="com.smallbeef.mybatis.bean.Employee">
	 	select * from tbl_employee
	 	<!-- where -->
	 	<where>
		 	<if test="id!=null">
		 		and id=#{id}
		 	</if>
		 	<if test="lastName!=null and lastName!= ''">
		 		and last_name like #{lastName}
		 	</if>
		 	<if test="email!=null and email.trim()!= ''">
		 		and email=#{email}
		 	</if> 
		 	<!-- ognl会进行字符串与数字的转换判断  "0"==0 -->
		 	<if test="gender==0 or gender==1">
		 	 	and gender=#{gender}
		 	</if>
	 	</where>
	 </select>

where 会自动剔除多出来的 第一个前缀 and 或者 or

可以看见,上述的做法依然存在漏洞,
如果我们的写法是把and放在后面:

<select id="getEmpsByConditionIf" resultType="com.smallbeef.mybatis.bean.Employee">
	 	select * from tbl_employee
	 	<where>
		 	<if test="id!=null">
		 		id=#{id} and 
		 	</if>
		 	<if test="lastName!=null and lastName!= ''">
		 		last_name like #{lastName} and 
		 	</if>
		 	<if test="email!=null and email.trim()!= ''">
		 		email=#{email} and 
		 	</if> 
		 	<!-- ognl会进行字符串与数字的转换判断  "0"==0 -->
		 	<if test="gender==0 or gender==1">
		 	 	gender=#{gender}
		 	</if>
	 	</where>
	 </select>

如果 gender 为空,则查询语句为

select * from tbl_employee id = ? and last_name = ? and email = ? and

语法出错,因为 where 只能剔除多出来的 第一个前缀 and 或者 or

所以,在使用where标签的时候,建议把and写在语句的前面

3. trim 自定义字符串截取

对于上述把and写在后面的写法,我们可以使用 trim 标签 自定义字符串的截取规则

trim 标签中的属性:

  • prefix="" : 前缀:trim标签体中是整个字符串拼串 后的结果。
    prefix给拼串后的整个字符串加一个前缀
  • prefixOverrides="" : 前缀覆盖:
    去掉整个字符串前面多余的字符
  • suffix="" : 后缀
    suffix给拼串后的整个字符串加一个后缀
  • suffixOverrides="" 后缀覆盖:
    去掉整个字符串后面多余的字符
<select id="getEmpsByConditionTrim" resultType="com.smallbeef.mybatis.bean.Employee">
	 	select * from tbl_employee
	 	<trim prefix="where" suffixOverrides="and">
	 		<if test="id!=null">
		 		id=#{id} and
		 	</if>
		 	<if test="lastName!=null &amp;&amp; lastName!=&quot;&quot;">
		 		last_name like #{lastName} and
		 	</if>
		 	<if test="email!=null and email.trim()!=&quot;&quot;">
		 		email=#{email} and
		 	</if> 
		 	<!-- ognl会进行字符串与数字的转换判断  "0"==0 -->
		 	<if test="gender==0 or gender==1">
		 	 	gender=#{gender}
		 	</if>
		 </trim>
	 </select>

4. choose 分支选择

choose (when, otherwise):分支选择;
等同于 带了 break 的 swtich-case
如果带了id就用id查,如果带了lastName就用lastName查 ; 只会进入其中一个查询语句

 <select id="getEmpsByConditionChoose" resultType="com.smallbeef.mybatis.bean.Employee">
	 	select * from tbl_employee 
	 	<where>
	 		<!-- 如果带了id就用id查,如果带了lastName就用lastName查;只会进入其中一个 -->
	 		<choose>
	 			<when test="id!=null">
	 				id=#{id}
	 			</when>
	 			<when test="lastName!=null">
	 				last_name like #{lastName}  // 模糊查询
	 			</when>
	 			<when test="email!=null">
	 				email = #{email}
	 			</when>
	 			<otherwise>
	 				gender = 0 //如果上述条件都不符合,则执行此条语句
	 			</otherwise>
	 		</choose>
	 	</where>
	 </select>

如果 id != null

Employee employee = new Employee(1, "Admin", null, null);
List<Employee> emps = mapper.getEmpsByConditionIf(employee );

则查询语句为

select * from tbl_employee id = 1

如果 全为 null

Employee employee = new Employee(null, null, null, null);
List<Employee> emps = mapper.getEmpsByConditionIf(employee );

则查询语句为

select * from tbl_employee gender = 0 

5. set 更新

我们之前的更新操作语句是这样的

<update id="updateEmp">
		update tbl_employee 
		set last_name=#{lastName},email=#{email},gender=#{gender}
		where id=#{id}
	</update>

需要进行全字段更新
比如:已有数据库信息 id = 1 , lastName = Jack, email = 123, gender = 1;
我们想要更新它的lastName,则:

Employee employee = new Employee(1, "Admin", 123, 1);
List<Employee> emps = mapper.updateEmp(employee );

set 标签用来执行更新操作,只更新需要更新的字段

<!--public void updateEmp(Employee employee);  -->
	 <update id="updateEmp">
	 	<!-- Set标签的使用 -->
	 	update tbl_employee 
		<set>
			<if test="lastName!=null">
				last_name=#{lastName},
			</if>
			<if test="email!=null">
				email=#{email},
			</if>
			<if test="gender!=null">
				gender=#{gender}
			</if>
		</set>
		where id=#{id} 
	 </update>

set 标签会自动剔除多余的

比如:已有数据库信息 id = 1 , lastName = Jack, email = 123, gender = 1;
我们想要更新它的lastName,则:

Employee employee = new Employee(1, "Admin", null, null);
List<Employee> emps = mapper.updateEmp(employee );

可以看见 email 和 gender 都为空,即该字段不被更新,保持不变。

6. foreach 遍历集合

foreach 标签中的属性:

  • collection:指定要遍历的集合:
    list类型的参数会特殊处理封装在map中,map的key就叫list

  • item:将当前遍历出的元素赋值给指定的变量

  • separator:每个元素之间的分隔符

  • open:遍历出所有结果拼接一个开始的字符

  • close:遍历出所有结果拼接一个结束的字符

  • index:索引。遍历list的时候是index就是索引,item就是当前值
    遍历map的时候index表示的就是map的key,item就是map的值

  • #{变量名} 就能取出变量的值也就是当前遍历出的元素

批量查询

//查询员工id'在给定集合中的
public List<Employee> getEmpsByConditionForeach(@Param("ids")List<Integer> ids);
<!--public List<Employee> getEmpsByConditionForeach(List<Integer> ids);  -->
	 <select id="getEmpsByConditionForeach" resultType="com.smallbeef.mybatis.bean.Employee">
	 	select * from tbl_employee
	 	<foreach collection="ids" item="item_id" separator=","
	 		open="where id in(" close=")">
	 		#{item_id}
	 	</foreach>
	 </select>

测试:

List<Employee> list = mapper.getEmpsByConditionForeach(Arrays.asList(1,2,3,4));
for (Employee emp : list) 
	System.out.println(emp);

批量保存

public void addEmps(@Param("emps")List<Employee> emps);
 <!--public void addEmps(@Param("emps")List<Employee> emps);  -->
	 <!--MySQL下批量保存:可以foreach遍历   mysql支持values(),(),()语法-->
	<insert id="addEmps">
	 	insert into tbl_employee
		values
		<foreach collection="emps" item="emp" separator=",">
			(#{emp.lastName},#{emp.email},#{emp.gender},#{emp.dept.id})
		</foreach>
	 </insert>

测试:

@Test
	public void testBatchSave() throws IOException{
		String resource = "mybatis-config.xml";
		InputStream inputStream = Resources.getResourceAsStream(resource);
		SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
		SqlSession openSession = sqlSessionFactory.openSession();
		try{
			EmployeeMapperDynamicSQL mapper = openSession.getMapper(EmployeeMapperDynamicSQL.class);
			List<Employee> emps = new ArrayList<>();
			emps.add(new Employee(null, "smith0x1", "[email protected]", "1",new Department(1)));
			emps.add(new Employee(null, "allen0x1", "[email protected]", "0",new Department(1)));
			mapper.addEmps(emps);
			openSession.commit();
		}finally{
			openSession.close();
		}
	}

7. 两个内置参数 _databaseId / _parameter

两个内置参数:
不只是方法传递过来的参数可以被用来判断,取值
mybatis默认还有两个内置参数:

  • _parameter : 代表整个参数
    单个参数:_parameter就是这个参数
    多个参数:参数会被封装为一个map;_parameter就是代表这个map

  • _databaseId : 如果配置了databaseIdProvider标签。
    _databaseId就是代表当前数据库的别名oracle

  <!--public List<Employee> getEmpsTestInnerParameter(Employee employee);  -->
	  <select id="getEmpsTestInnerParameter" resultType="com.smakk.mybatis.bean.Employee">

	  		<if test="_databaseId=='mysql'">
	  			select * from tbl_employee
	  			<if test="_parameter!=null">
	  				where last_name like #{lastName}
	  			</if>
	  		</if>
	  		<if test="_databaseId=='oracle'">
	  			select * from employees
	  			<if test="_parameter!=null">
	  				where last_name like #{_parameter.lastName}
	  			</if>
	  		</if>
	  </select>

8. bind 绑定

bind 元素可以从 OGNL 表达式中创建一个变量并将其绑定到上下文。
比如:

 <!--public List<Employee> getEmpsTestInnerParameter(Employee employee);  -->
	  <select id="getEmpsTestInnerParameter" resultType="com.atguigu.mybatis.bean.Employee">
	  		<bind name="_lastName" value="'%'+lastName+'%'"/>
	  		<if test="_databaseId=='mysql'">
	  			select * from tbl_employee
	  			<if test="_parameter!=null">
	  				where last_name like #{lastName}
	  			</if>
	  		</if>
	  </select>

测试:

Employee employee2 = new Employee();
employee2.setLastName("e");
List<Employee> list = mapper.getEmpsTestInnerParameter(employee2);
for (Employee employee : list) 
	System.out.println(employee);

lastName 的值 e 被 bind 拼接成 %e%,即由精确查询—> 模糊查询

9. sql 抽取可重用的 sql 片段

抽取可重用的sql片段。方便后面引用

  • sql 抽取:经常将要查询的列名,或者插入用的列名抽取出来方便引用
  • include 来引用已经抽取的sql:
  • include 还可以自定义一些 property,可在sql标签内部通过${prop} 取出对应值
    不能使用这种方式 #{prop}

示例如下:

  <sql id="insertColumn">
  		<if test="_databaseId=='oracle'">
  			employee_id,last_name,email,${testColumn}
  		</if>
  		<if test="_databaseId=='mysql'">
  			last_name,email,gender,d_id
  		</if>
  </sql>
<insert id="addEmps" databaseId="oracle">
	 	insert into employees(
	 		<!-- 引用外部定义的sql -->
	 		<include refid="insertColumn">
	 			<property name="testColomn" value="abc"/>
	 		</include>
	 	)
	 	<foreach collection="emps" item="emp" separator="union"
	 		open="select employees_seq.nextval,lastName,email from("
	 		close=")">
	 		select #{emp.lastName} lastName,#{emp.email} email from dual
	 	</foreach>
	 </insert>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章