mybatis 使用 choose when otherwise 規避異常

也是在工作中遇到小問題,查到原因後依舊是沒有規避到空值。

簡化的場景

假設我們有一張學生表:

create table students(
	name varchar(255) not null,
    sex varchar(255) not noll,
    score int(11);
)

這張表也很簡單,就姓名、性別、成績三個字段。

也是很簡單的一個場景,但能說明問題。

需求:將一些學生的成績減去10分。

<update id="updateStudentScore">
    update student
    set core = score - 10
    where name in 
    <foreach collection="names="item" separator="," open="(" close=")">
      #{item}
    </foreach>
</update>

這種寫法正常情況時完全ok的,但是當names是個空列表時,就會報異常。

使用 choose when otherwise

<update id="updateStudentScore">
    update student
    set core = score - 10
    where name in 
    <choose>
      <when test="names == null || names.isEmpty()">
        where 1=0
      </when>
      <otherwise>
        where name in
        <foreach collection="names" index="index" item="item" separator="," open="(" close=")">
          #{item}
        </foreach>
      </otherwise>
    </choose>
</update>

這種動態SQL就可以規避掉空列表異常的現象,類似於java的 if..else if..else。當然也可以在外圍判斷類表是否爲空,如果是,則不執行update score操作,這也是可以的,當然,最終是要根據嚐盡確定解決辦法。

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