MyBatis_MyBatis之动态SQL之常用OGNL表达式

1.引入

   我们知道,我们在使用JDBC、DBUtils等框架的时候,我们经常会遇到一个问题就是拼接SQL。这一个是比较麻烦的一个过程。我们对SQL的拼接需要比较严谨,经常会出现拼接的SQL无法运行的情况。那么针对这一个情况,MyBatis使用动态SQL帮助我们解决这一个问题。

   动态 SQL是MyBatis强大特性之一。极大的简化我们拼装SQL的操作。动态 SQL 元素和使用 JSTL 或其他类似基于 XML 的文本处理器相似。
   MyBatis 采用功能强大的基于 OGNL 的表达式来简化操作。一下是常用的几个操作语句关键词:
– if
– choose (when, otherwise)
– trim (where, set)
– foreac

 

2.OGNL的表达式

   OGNL是Object-Graph Navigation Language的缩写,它是一种功能强大的表达式语言,通过它简单一致的表达式语法,可以存取对象的任意属性,调用对象的方法,遍历整个对象的结构图,实现字段类型转化等功能。它使用相同的表达式去存取对象的属性。这样可以更好的取得数据。

 

3.常用动态SQL标签内容_if判断

(1).功能

         if语句的功能是按照条件判断进行选取。

(2).示例

          需求:在映射文件中,查询员工,要求,携带了哪个字段查询条件就带上这个字段的值

          代码示例:

 <!-- public List<Employee> getEmpsByConditionIf(Employee employee); -->
	<select id="getEmpsByConditionIf" resultType="com.atguigu.mybatis.bean.Employee">
	 	select * from tbl_employee	
        where 	
		 	<!-- test:判断表达式(OGNL)
		 	OGNL参照PPT或者官方文档。
		 	  	 c:if  test
		 	从参数中取值进行判断
		 	
		 	遇见特殊符号应该去写转义字符:
		 	&&:and的意思,也可以使用and,但是需要使用转义字符&amp;&amp;
            &quot;&quot;表示的是单引号的空串
		 	-->

		 	<if test="id!=null">
		 		id=#{id}
		 	</if>
		 	<if test="lastName!=null &amp;&amp; lastName!=&quot;&quot;">
		 		and last_name like #{lastName}
		 	</if>
		 	<if test="email!=null and email.trim()!=&quot;&quot;">
		 		and email=#{email}
		 	</if> 
		 	<!-- ognl会进行字符串与数字的转换判断  "0"==0 -->
		 	<if test="gender==0 or gender==1">
		 	 	and gender=#{gender}
		 	</if>	 
	 </select>

       拼接的SQL:select * from tbl_employee where id=? and last_name like ?

 也就是说使用if作为判断,这一个时候使用的sql的拼接他会是给你传递什么值就会在sql的后面吧条件进行一个拼接。

 

4.常用动态SQL标签内容_where

  (1).引入:查询的时候如果某些条件没带可能sql拼装会有问题,也就是如何在3的操作做中没有传递给sql所需对应的id的值,那么这一个时候sql就变成了:select * from tbl_employee where and last_name like ?,那显然这样是有sql的语法问题。那么如何解决这一个问题呢?

          ①、给where后面加上1=1,以后的条件都and xxx.

          ②、mybatis使用where标签来将所有的查询条件包括在内。

(2).按照所给的参数值,对所设置的参数进行一个筛选,一般需要与其他的连用。mybatis就会将where标签中拼装的sql,多出             来的and或者or去掉where只会去掉第一个多出来的and或者or。

(3).示例:改进3中的操作

<select id="getEmpsByConditionIf" resultType="com.atguigu.mybatis.bean.Employee">
	 	select * from tbl_employee
	 	<!-- where -->
	 	<where>
		 	<!-- test:判断表达式(OGNL)
		 	OGNL参照PPT或者官方文档。
		 	  	 c:if  test
		 	从参数中取值进行判断
		 	
		 	遇见特殊符号应该去写转义字符:
		 	&&:
		 	-->
		 	<if test="id!=null">
		 		id=#{id}
		 	</if>
		 	<if test="lastName!=null &amp;&amp; lastName!=&quot;&quot;">
		 		and last_name like #{lastName}
		 	</if>
		 	<if test="email!=null and email.trim()!=&quot;&quot;">
		 		and email=#{email}
		 	</if> 
		 	<!-- ognl会进行字符串与数字的转换判断  "0"==0 -->
		 	<if test="gender==0 or gender==1">
		 	 	and gender=#{gender}
		 	</if>
	 	</where>
	 </select>

使用了where标签以后,它就会取出掉第一个SQL值没有参数的问题,但是这样仅仅只是解决了一部分的问题,如果不是第一个参数没有传递,而是后面的参数没有传递,同样也是会出现问题的。

 

5.常用动态SQL标签内容_trim

(1).引入:查询的时候如果某些条件没带可能sql拼装会有问题。在拼装sql的时候,由于where只能够解决第一个SQL的问题。            当没有传递的参数出现在后面几个的时候where没有办法解决,这一个时候我们就需要使用trim。

(2).功能:用于解决在sql拼装中后面多出的and或者or,使用情况如下:

<!-- 后面多出的and或者or where标签不能解决 
	 	prefix="":前缀:trim标签体中是整个字符串拼串 后的结果。
	 			prefix给拼串后的整个字符串加一个前缀 
	 	prefixOverrides="":
	 			前缀覆盖: 去掉整个字符串前面多余的字符
	 	suffix="":后缀
	 			suffix给拼串后的整个字符串加一个后缀 
	 	suffixOverrides=""
	 			后缀覆盖:去掉整个字符串后面多余的字符	 			
-->

(3).示例:改进3中的操作

 <select id="getEmpsByConditionTrim" resultType="com.atguigu.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>

6.常用动态SQL标签内容_choose

(1).功能:用于进行分支选择,类似于java中的switch...case的使用。满足哪一个情况就进行选择并执行。如果满足多个情                  况,   那么这一个时候就只会选择第一个满足的条件。

(2).示例:

          需求分析:编写一条sql,使其满足:如果带了id就用id查,如果带了lastName就用lastName查;只会进入其中一个

<select id="getEmpsByConditionChoose" resultType="com.atguigu.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>

 

7.常用动态SQL标签内容_set

(1).功能:主要是用于设置参数值,用于更新操作。

(2).示例:

         需求:根据传递的参数,哪一个参数不为空,就按照id对那一个参数进行更新操作。

<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>


//上述的代码我们也可以使用trim进行一个实现

<update id="updateEmp">	 			
		update tbl_employee 
		<trim prefix="set" suffixOverrides=",">
			<if test="lastName!=null">
				last_name=#{lastName},
			</if>
			<if test="email!=null">
				email=#{email},
			</if>
			<if test="gender!=null">
				gender=#{gender}
			</if>
		</trim>
		where id=#{id} 
 </update>

 

8.常用动态SQL标签内容_foreach

(1).功能:对集合进行数据的遍历功能

(2).示例:

查询员工id'在给定集合中的对象集合

①:查询方法

//查询员工id'在给定集合中的
public List<Employee> getEmpsByConditionForeach(@Param("ids")List<Integer> ids);

②:配置文件内容

 <select id="getEmpsByConditionForeach" resultType="com.atguigu.mybatis.bean.Employee">
	 	select * from tbl_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="item_id" separator=","
	 		open="where id in(" close=")">
	 		#{item_id}
	 	</foreach>
	 </select>

③:调用测试

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

注意:我们在使用foreach的时候,需要注意如何正确的把参数进行一个准确的传递。

 

9.常用动态SQL标签内容_foreach实现批量保存

(1).定义批量存储的方法

public void addEmps(@Param("emps")List<Employee> emps);

(2).MySQL进行批量插入操作

MySQL下批量保存:可以foreach遍历   mysql支持values(),(),()语法

(3).进行配置文件配置

<insert id="addEmps">
	 	insert into tbl_employee(
	 		<include refid="insertColumn"></include>
	 	) 
		values
		<foreach collection="emps" item="emp" separator=",">
			(#{emp.lastName},#{emp.email},#{emp.gender},#{emp.dept.id})
		</foreach>
</insert>

(4).调用测试

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();

 

Guess you like

Origin blog.csdn.net/u013185175/article/details/107849586