【Mybatis】动态sql & 抽取可重用sql

抽取可重用的sql片段

抽取<sql id="xx"></sql>

使用<include refid="xx"></inculde>

<select id="getEmpsByDid" resultType="com.atguigu.mybatis.beans.Employee">
    <include refid="selectEmployeeSQL"></include> 
    from tbl_employee where d_id = #{did}
</select>
	

<!--抽取可重用的SQL片段 -->
<sql id="selectEmployeeSQL">
    select id ,last_name,email,gender
</sql>

动态sql

MyBatis 采用功能强大的基于 OGNL 的表达式来简化操作

OGNL( Object Graph Navigation Language )对象图导航语言,这是一种强大的

  • 表达式语言,通过它可以非常方便的来操作对象属性。 类似于我们的EL,SpEL等

  • 访问对象属性:person.name

  • 调用方法: person.getName()

  • 调用静态属性/方法:

  • 调用构造方法:

  • 运算符: +,-*,/,%

  • 逻辑运算符: in ,not in ,> ,>= ,< ,<= ,== ,!= ,or,and

注意:xml中特殊符号如”,>,<等这些都需要使用转义字符

if where

  1. If用于简单的判断.

  2. Where用于解决SQL语句中where关键字以及条件中第一个and或者or的问题

# public List<Employee>  getEmpsByConditionIfWhere(Employee Condition);
<select id="getEmpsByConditionIfWhere" 	resultType="com.atguigu.mybatis.beans.Employee">
        select id, last_name, email, gender from tbl_employee 

    <where> 	
        <!--
  现在使用where标签也可完美解决,在SQL语句中提供WHERE关键字,并且要解决第一个条件就出现的and 或者是 or的问题 
-->
      
        <if test="id!=null">
            and id = #{id }
        </if>
        
        <if test="lastName!=null&amp;&amp;lastName!=&quot;&quot;">
            and  last_name = #{lastName}
        </if>
        
        <if test="email!=null and email.trim()!=''">
            and  email = #{email}
        </if>
        
        <if test="gender==0 or gender==1">
            and  gender = #{gender}
        </if>
    </where>
</select>

choose(when,otherwise)

用于分支判断,类似于java中的switch case,只会满足所有分支中的一个

<!--public List<Employee>  getEmpsByConditionChoose(Employee Condition);-->
<select id="getEmpsByConditionChoose" resultType="com.atguigu.mybatis.beans.Employee">
    select id ,last_name, email,gender from tbl_employee
    <where>
        <choose>
            <when test="id!=null">
                id = #{id}
            </when>
            
            <when test="lastName!=null">
                last_name = #{lastName}
            </when>
            
            <when test="email!=null">
                email = #{email}
            </when>
            
            <otherwise>
                gender = 'm'
            </otherwise>
        </choose>
    </where>
</select>

choose 类似 switch,when 类似 case,otherwise 类似 default

trim

trim 可以在条件判断完的SQL语句前后 添加或者去掉指定的字符

prefix 添加前缀
prefixOverrides 去掉前缀
suffix 添加后缀
suffixOverrides 去掉后缀
#public List<Employee>  getEmpsByConditionTrim(Employee Condition);
<select id="getEmpsByConditionTrim" resultType="com.atguigu.mybatis.beans.Employee">
		select id , last_name ,email  , gender  from tbl_employee 
    <!--添加where前缀,若后缀是and则删除-->
    <trim prefix="where"  suffixOverrides="and">
        <if test="id!=null">
            id = #{id} and
        </if>
        <if test="lastName!=null &amp;&amp; lastName!=&quot;&quot;">
            last_name = #{lastName} and
        </if>
        <if test="email!=null and email.trim()!=''">
            email = #{email} and
        </if>
        <if test="&quot;m&quot;.equals(gender) or &quot;f&quot;.equals(gender)">
            gender = #{gender}
        </if>
    </trim>
</select>

set

用于解决修改操作中SQL语句中可能多出逗号的问题


<!--public void  updateEmpByConditionSet(Employee Condition); -->
<update id="updateEmpByConditionSet">
		update  tbl_employee  
		<set>
			<if test="lastName!=null and lastName!=''">
				 last_name = #{lastName},
			</if>
			<if test="email!=null and email.trim()!=''">
				 email = #{email} ,
			</if>
			<if test="gender==0 or gender==1">
				gender = #{gender} 
			</if>
		</set>
		 where id =#{id}
	</update>

foreach

动态 SQL 的另外一个常用的必要操作是需要对一个集合进行遍历,通常是在构建 IN 条件语句的时候。

foreach 主要用于循环迭代
item 当前从集合中迭代出的元素
collection 要迭代的集合
open 开始字符
close 结束字符
separator 元素与元素之间的分隔符
index 迭代的是List集合: index表示的当前元素的下标
迭代的Map集合: index表示的当前元素的key

  <!--  public List<Employee>  getEmpsByIds(@Param("ids")List<Integer> ids )  -->
<select id="getEmpsByIds" resultType="com.atguigu.mybatis.beans.Employee">
    <!--
  select * from tbl_employee where id in(?,?,?);
   select * from tbl_employee where id = ?  or id = ?  or id = ? 
 -->
 
    select id ,last_name ,email, gender from  tbl_employee 
    where id  in
    <foreach collection="ids" item="currId" open=" (" close=")" separator=",">
        #{currId}
    </foreach>
</select>

批量操作

添加

insert into tbl_employee(x,x,x) values(?,?,?),(?,?,?),(?,?,?)
<!--public void addEmps(@Param("emps")List<Employee> emps );-->    
<insert id="addEmps">
		insert into tbl_employee(last_name, email,gender ) values 
		<foreach collection="emps" item="emp" separator=",">
			(#{emp.lastName},#{emp.email},#{emp.gender})
		</foreach>
</insert>

删除

delete from tbl_employee where id in(?,?,?)

修改

update tbl_employee set  last_name = #{lastName} ...where id = #{id};
		 update tbl_employee set  last_name = #{lastName} ...where id = #{id};
		 update tbl_employee set  last_name = #{lastName} ...where id = #{id};

默认情况下, JDBCB不允许将多条SQL通过;拼成一个字符串。 可以在连接的url后面加上一个参数: allowMultiQueries=true

posted @ 2021-03-26 11:03  至安  阅读(269)  评论(0)    收藏  举报