mybatis的動態sql

MyBatis 的一個強大的特性之一通常是它的動態 SQL 能力。 如果你有使用 JDBC 或其他 相似框架的經驗,你就明白條件地串聯 SQL 字符串在一起是多麼的痛苦,確保不能忘了空 格或在列表的最後省略逗號。動態 SQL 可以徹底處理這種痛苦。

基本標籤:

  • if
  • choose (when, otherwise)
  • trim (where, set)
  • foreach

if(用於多個參數查詢)

if 用在處理where後面跟一個條件

List<Employee> queryEmployee(@Param("name") String name,@Param("gradeid") int gradeid);

當方法有多個的參數 需要使用@Param指明將形參給xml文件中的那個參數

說明:
在這裏插入圖片描述

choose, when, otherwise(相當於Java中的switch、case、default用法)

<select id="findActiveBlogLike" 
     parameterType="Blog" resultType="Blog">
  SELECT * FROM BLOG WHERE state = ‘ACTIVE’
  <choose>
    <when test="title != null">
      AND title like #{title}
    </when>
    <when test="author != null and author.name != null">
      AND author_name like #{author.name}
    </when>
    <otherwise>
      AND 1 = 1
    </otherwise>
  </choose>
</select>

當第一個when標籤執行時後面的when標籤將不會執行

Where

如果查詢語句後面有多個條件
如果 第一個 if 語句成立則將在語句前面加上 where 並且去掉 if 語句中的 and 或者 or 關鍵字(簡化了 jdbc 中 SQL 憑藉中的 where 1=1 的操作)

<select id="queryByIntroduceAndCityId" resultType="ToursInfo">
        SELECT id,introduce,pubTime,price,cityId
        from toursInfo
        <where>
            <if test="intro!=null">
                and introduce like CONCAT('%',#{intro},'%')
            </if>
            <if test="cId!=null">
                and cityId =#{cId}
            </if>
        </where>
    </select>

Set

場景: 更新 頁面將需要更新的值傳到後臺 如果哪個屬性不需要更新就可以使用

在這裏插入圖片描述
映射文件

<update id="updateEmployee">
	UPDATE employee  
	<set>
	<if test="name1 !=null">`NAME`=#{name1},</if>
	<if test="sex !=null">sex=#{sex},</if>
	<if test="hiredate !=null">hiredate=#{hiredate},</if>
	<if test="dept.deptno !=null">deptno=#{dept.deptno}</if>
	</set>
	 where id=#{id}
</update>

測試類

// 1.獲取InputStream
		InputStream iStream = Test.class.getClassLoader().getResourceAsStream("config.xml");
		// 2.獲取sqlsessionfactory
		SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(iStream);
		// 3.獲取sqlsession
		SqlSession session = factory.openSession();
		// 4.通過代理獲取接口的對象
		EmployeeDao eDao = session.getMapper(EmployeeDao.class);
		//更新
		   Employee employee=new Employee();
		   employee.setId(47);
		  Dept dept=new Dept();
		  /*  dept.setDeptno(1);*/
		   employee.setDept(dept);
		   employee.setName1("彭大大");
		    eDao.updateEmployee(employee);
		 session.commit();

Foreach:批量刪除

1.參數爲list集合

Sql語句:DELETE from employee where id in ( 39,40,12) id爲動態的
在這裏插入圖片描述
xml中
item="id"代表循環遍歷的臨時變量名
collection=“list” 參數爲List集合 該屬性值爲list

<delete id="deleteEmployee">
	DELETE  from employee where id in
	<foreach collection="list" open="(" close=")" separator="," item="id" >
	     #{id}
	</foreach>
</delete>

測試類

public static void main(String[] args) {
		// 1.獲取InputStream
		InputStream iStream = Test.class.getClassLoader().getResourceAsStream("config.xml");
		// 2.獲取sqlsessionfactory
		SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(iStream);
		// 3.獲取sqlsession
		SqlSession session = factory.openSession();
		// 4.通過代理獲取接口的對象
		EmployeeDao eDao = session.getMapper(EmployeeDao.class);
		  
		List ids=new ArrayList();
		//in(39,40,12)
		ids.add(17);
		ids.add(18);
		
		 eDao.deleteEmployee(ids);
		 session.commit();

	}
2.參數爲Map集合

參數爲map集合
批量刪除 並限制部門編號
sql: DELETE from employee where id in(37,45,47) and deptno=2
分析:1個參數爲集合,1個參數爲單個值
Foreach遍歷Map通過key取值
在這裏插入圖片描述
xml

<delete id="deleteEmployee">
		DELETE from employee where id in
		<foreach collection="ids" open="(" close=")" separator=","
			item="id">
			#{id}
		</foreach>
		and deptno=#{deptno}
</delete>

測試類:
在這裏插入圖片描述
分析圖:
在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章