mybatis動態SQL之 —— 武功祕籍(一)

mybatis祕籍之—— 標籤

在這裏插入圖片描述

mybtis祕籍之 —— (CRUD) SQL語句

insert

  1. id :唯一的標識符
  2. parameterType:傳給此語句的參數的全路徑名或別名 例:com.test.poso.User
<insert id="insert" parameterType="Object">
    insert into student (student_id,stydent_name) values (#{studentId},#{stydentName})
</insert>

delete

  1. id :唯一的標識符
  2. parameterType:傳給此語句的參數的全路徑名或別名 例:com.test.poso.User
<delete id="deleteById" parameterType="Object">
    delete from student where id=#{id}
</delete>

update

  1. id :唯一的標識符
  2. parameterType:傳給此語句的參數的全路徑名或別名 例:com.test.poso.User
<update id="alter" >
      	  UPDATE student SET student_name= #{studentName} where  student_id= #{studentId}
</update>

select

  1. id :唯一的標識符
  2. parameterType:傳給此語句的參數的全路徑名或別名 例:com.test.poso.User 或 user
  3. resultType:語句返回值類型或別名。注意,如果是集合,那麼這裏填寫的是集合的泛型,而不是集合本身(resultType 與 resultMap不能並用)
<select id="findStudentById" resultMap="BaseResultMap" parameterType="Object">
    select * from student where id=#{id}
</select>

mybatis祕籍之——動態SQL拼接

if 語句

if 標籤通常用於 WHERE 後面,通過判斷參數值來決定是否使用某個條件、插入某個字段的值。

<select id="findStudentById" resultMap="BaseResultMap" parameterType="Object">
    select * from student where 1=1
    <if test="studentId != null and studentId != ''">
    	and student_id =#{studentId }
    </if>
    <if test="studentName!= null and studentName!= ''">
    	and student_name =#{studentName}
    </if>
</select>

foreach語句

foreach 標籤主要用於構建 in 條件,可在 sql 中對集合進行迭代。也常用到批量刪除、添加等操作中。

屬性:

  1. collection:collection 屬性的值有三個分別是 list、array、map 三種,分別對應的參數類型爲:List、數組、map 集合。
  2. item :表示在迭代過程中每一個元素的別名
  3. index :表示在迭代過程中每次迭代到的位置(下標)
  4. open :前綴
  5. close :後綴
  6. separator :分隔符,表示迭代時每個元素之間以什麼分隔
<!-- in查詢所有,不分頁 -->
<select id="selectIn" resultMap="BaseResultMap">
    select name,hobby from student where id in
    <foreach item="item" index="index" collection="list" open="(" separator="," close=")">
        #{item}
    </foreach>
</select>

choose語句

choose類似於 Java 的 switch 語句,choose 爲 switch,when 爲 case,otherwise 則爲 default。

按順序判斷 when 中的條件出否成立,如果有一個成立,則 choose 結束。當 choose 中所有 when的條件都不滿則時,則執行 otherwise 中的 sql。

if 是與(and)的關係,而 choose 是或(or)的關係。

<select id="getStudentListChoose" parameterType="Student" resultMap="BaseResultMap">
    SELECT * from STUDENT WHERE 1=1
    <where>
        <choose>
            <when test="Name!=null and student!='' ">
                AND name LIKE CONCAT(CONCAT('%', #{student}),'%')
            </when>
            <when test="hobby!= null and hobby!= '' ">
                AND hobby = #{hobby}
            </when>
            <otherwise>
                AND AGE = 15
            </otherwise>
        </choose>
    </where>
</select>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章