mybatis動態SQL語句

   有些時候, sql 語句 where 條件中,須要一些安全判斷,例如按某一條件查詢時若是傳入的參數是空,此時查詢出的結果極可能是空的,也許咱們須要參數爲空時,是查出所有的信息。使用 Oracle 的序列、 mysql 的函數生成 Id 。這時咱們可使用動態 sql

       下文均採用mysql語法和函數(例如字符串連接函數CONCAT)。java

3.1 selectKey 標籤

       insert語句中,在Oracle常用序列、在MySQL中使用函數來自動生成插入表的主鍵,並且須要方法能返回這個生成主鍵。使用myBatisselectKey標籤能夠實現這個效果。mysql

       下面例子,使用mysql數據庫自定義函數nextval('student'),用來生成一個key,並把他設置到傳入的實體類中的studentId屬性上。因此在執行完此方法後,邊能夠經過這個實體類獲取生成的keysql

<mappers> <mapper resource="com/liming/manager/data/mappers/UserMapper.xml" /> <mapper resource="com/liming/manager/data/mappers/StudentMapper.xml" /> <mapper resource="com/liming/manager/data/mappers/ClassMapper.xml" /> <mapper resource="com/liming/manager/data/mappers/TeacherMapper.xml" /> </mappers>

Java接口與XML文件在一個相對路徑下時,能夠不在myBatis配置文件的mappers中聲明。數據庫

 


SQL 映射XML 文件一些初級的元素:apache


1. cache – 配置給定模式的緩存
2. cache-ref – 從別的模式中引用一個緩存
3. resultMap – 這是最複雜而卻強大的一個元素了,它描述如何從結果集中加載對象
4. sql – 一個能夠被其餘語句複用的SQL 塊
5. insert – 映射INSERT 語句
6. update – 映射UPDATE 語句
7. delete – 映射DELEETE 語句
8. select  -  映射SELECT語句數組

 


2.1 resultMap

        resultMap 是MyBatis 中最重要最強大的元素了。你可讓你比使用JDBC 調用結果集省掉90%的代碼,也可讓你作許多JDBC 不支持的事。現實上,要寫一個等同相似於交互的映射這樣的複雜語句,可能要上千行的代碼。ResultMaps 的目的,就是這樣簡單的語句而不須要多餘的結果映射,更多複雜的語句,除了只要一些絕對必須的語句描述關係之外,不再須要其它的。緩存

resultMap屬性:type爲java實體類;id爲此resultMap的標識。安全

 

 resultMap能夠設置的映射:app


1. constructor – 用來將結果反射給一個實例化好的類的構造器ide

a) idArg – ID 參數;將結果集標記爲ID,以方便全局調用
b) arg –反射到構造器的一般結果


2. id – ID 結果,將結果集標記爲ID,以方便全局調用


3. result – 反射到JavaBean 屬性的普通結果


4. association – 複雜類型的結合;多個結果合成的類型

a) nested result mappings – 幾resultMap 自身嵌套關聯,也能夠引用到一個其它上


5. collection –複雜類型集合a collection of complex types


6. nested result mappings – resultMap 的集合,也能夠引用到一個其它上


7. discriminator – 使用一個結果值以決定使用哪一個resultMap

a) case – 基本一些值的結果映射的case 情形

i. nested result mappings –一個case 情形自己就是一個結果映射,所以也能夠包括一些相同的元素,也能夠引用一個外部resultMap。

 

 

2.1.1 id、result

id、result是最簡單的映射,id爲主鍵映射;result其餘基本數據庫表字段到實體類屬性的映射。
  最簡單的例子:

 

<!-- 插入學生 自動主鍵--> <insert id="createStudentAutoKey" parameterType="liming.student.manager.data.model.StudentEntity" keyProperty="studentId"> <selectKey keyProperty="studentId" resultType="String" order="BEFORE"> select nextval('student') </selectKey> INSERT INTO STUDENT_TBL(STUDENT_ID, STUDENT_NAME, STUDENT_SEX, STUDENT_BIRTHDAY, STUDENT_PHOTO, CLASS_ID, PLACE_ID) VALUES (#{studentId}, #{studentName}, #{studentSex}, #{studentBirthday}, #{studentPhoto, javaType=byte[], jdbcType=BLOB, typeHandler=org.apache.ibatis.type.BlobTypeHandler}, #{classId}, #{placeId}) </insert>

調用接口方法,和獲取自動生成key


StudentEntity entity = new StudentEntity(); entity.setStudentName("黎明你好"); entity.setStudentSex(1); entity.setStudentBirthday(DateUtil.parse("1985-05-28")); entity.setClassId("20000001"); entity.setPlaceId("70000001"); this.dynamicSqlMapper.createStudentAutoKey(entity); System.out.println("新增學生ID: " + entity.getStudentId());

selectKey語句屬性配置細節:

 

屬性 描述 取值
keyProperty selectKey 語句生成結果須要設置的屬性。
resultType 生成結果類型,MyBatis 容許使用基本的數據類型,包括String int類型。
order

1BEFORE,會先選擇主鍵,而後設置keyProperty,再執行insert語句;

2AFTER,就先運行insert 語句再運行selectKey 語句。

BEFORE

AFTER
statementType MyBatis 支持STATEMENTPREPAREDCALLABLE 的語句形式, 對應Statement PreparedStatement CallableStatement 響應

STATEMENT

PREPARED

CALLABLE

 

3.2 if標籤

 

 if標籤可用在許多類型的sql語句中,咱們以查詢爲例。首先看一個很普通的查詢:

<!-- 查詢學生list,like姓名 --> <select id="getStudentListLikeName" parameterType="StudentEntity" resultMap="studentResultMap"> SELECT * from STUDENT_TBL ST WHERE ST.STUDENT_NAME LIKE CONCAT(CONCAT('%', #{studentName}),'%') </select>

可是此時若是studentName或studentSex爲null,此語句極可能報錯或查詢結果爲空。此時咱們使用if動態sql語句先進行判斷,若是值爲null或等於空字符串,咱們就不進行此條件的判斷,增長靈活性。

參數爲實體類StudentEntity。將實體類中全部的屬性均進行判斷,若是不爲空則執行判斷條件。

<!-- 2 if(判斷參數) - 將實體類不爲空的屬性做爲where條件 --> <select id="getStudentList_if" resultMap="resultMap_studentEntity" parameterType="liming.student.manager.data.model.StudentEntity"> SELECT ST.STUDENT_ID, ST.STUDENT_NAME, ST.STUDENT_SEX, ST.STUDENT_BIRTHDAY, ST.STUDENT_PHOTO, ST.CLASS_ID, ST.PLACE_ID FROM STUDENT_TBL ST WHERE <if test="studentName !=null "> ST.STUDENT_NAME LIKE CONCAT(CONCAT('%', #{studentName, jdbcType=VARCHAR}),'%') </if> <if test="studentSex != null and studentSex != '' "> AND ST.STUDENT_SEX = #{studentSex, jdbcType=INTEGER} </if> <if test="studentBirthday != null "> AND ST.STUDENT_BIRTHDAY = #{studentBirthday, jdbcType=DATE} </if> <if test="classId != null and classId!= '' "> AND ST.CLASS_ID = #{classId, jdbcType=VARCHAR} </if> <if test="classEntity != null and classEntity.classId !=null and classEntity.classId !=' ' "> AND ST.CLASS_ID = #{classEntity.classId, jdbcType=VARCHAR} </if> <if test="placeId != null and placeId != '' "> AND ST.PLACE_ID = #{placeId, jdbcType=VARCHAR} </if> <if test="placeEntity != null and placeEntity.placeId != null and placeEntity.placeId != '' "> AND ST.PLACE_ID = #{placeEntity.placeId, jdbcType=VARCHAR} </if> <if test="studentId != null and studentId != '' "> AND ST.STUDENT_ID = #{studentId, jdbcType=VARCHAR} </if> </select>

使用時比較靈活, new一個這樣的實體類,咱們須要限制那個條件,只須要附上相應的值就會where這個條件,相反不去賦值就能夠不在where中判斷。

public void select_test_2_1() { StudentEntity entity = new StudentEntity(); entity.setStudentName(""); entity.setStudentSex(1); entity.setStudentBirthday(DateUtil.parse("1985-05-28")); entity.setClassId("20000001"); //entity.setPlaceId("70000001"); List<StudentEntity> list = this.dynamicSqlMapper.getStudentList_if(entity); for (StudentEntity e : list) { System.out.println(e.toString()); } }

3.3 if + where 的條件判斷

       where中的條件使用的if標籤較多時,這樣的組合可能會致使錯誤。咱們以在3.1中的查詢語句爲例子,當java代碼按以下方法調用時:

@Test public void select_test_2_1() { StudentEntity entity = new StudentEntity(); entity.setStudentName(null); entity.setStudentSex(1); List<StudentEntity> list = this.dynamicSqlMapper.getStudentList_if(entity); for (StudentEntity e : list) { System.out.println(e.toString()); } }

若是上面例子,參數studentNamenull,將不會進行STUDENT_NAME列的判斷,則會直接導「WHERE AND」關鍵字多餘的錯誤SQL

 

這時咱們可使用where動態語句來解決。這個「where」標籤會知道若是它包含的標籤中有返回值的話,它就插入一個‘where’。此外,若是標籤返回的內容是以AND OR 開頭的,則它會剔除掉。

上面例子修改成:

<!-- 3 select - where/if(判斷參數) - 將實體類不爲空的屬性做爲where條件 --> <select id="getStudentList_whereIf" resultMap="resultMap_studentEntity" parameterType="liming.student.manager.data.model.StudentEntity"> SELECT ST.STUDENT_ID, ST.STUDENT_NAME, ST.STUDENT_SEX, ST.STUDENT_BIRTHDAY, ST.STUDENT_PHOTO, ST.CLASS_ID, ST.PLACE_ID FROM STUDENT_TBL ST <where> <if test="studentName !=null "> ST.STUDENT_NAME LIKE CONCAT(CONCAT('%', #{studentName, jdbcType=VARCHAR}),'%') </if> <if test="studentSex != null and studentSex != '' "> AND ST.STUDENT_SEX = #{studentSex, jdbcType=INTEGER} </if> <if test="studentBirthday != null "> AND ST.STUDENT_BIRTHDAY = #{studentBirthday, jdbcType=DATE} </if> <if test="classId != null and classId!= '' "> AND ST.CLASS_ID = #{classId, jdbcType=VARCHAR} </if> <if test="classEntity != null and classEntity.classId !=null and classEntity.classId !=' ' "> AND ST.CLASS_ID = #{classEntity.classId, jdbcType=VARCHAR} </if> <if test="placeId != null and placeId != '' "> AND ST.PLACE_ID = #{placeId, jdbcType=VARCHAR} </if> <if test="placeEntity != null and placeEntity.placeId != null and placeEntity.placeId != '' "> AND ST.PLACE_ID = #{placeEntity.placeId, jdbcType=VARCHAR} </if> <if test="studentId != null and studentId != '' "> AND ST.STUDENT_ID = #{studentId, jdbcType=VARCHAR} </if> </where> </select>

3.4 if + set 的更新語句

update語句中沒有使用if標籤時,若是有一個參數爲null,都會致使錯誤。

當在update語句中使用if標籤時,若是前面的if沒有執行,則或致使逗號多餘錯誤。使用set標籤能夠將動態的配置SET 關鍵字,和剔除追加到條件末尾的任何不相關的逗號。

 

       使用if+set標籤修改後,若是某項爲null則不進行更新,而是保持數據庫原值。以下示例:

<!-- 4 if/set(判斷參數) - 將實體類不爲空的屬性更新 --> <update id="updateStudent_if_set" parameterType="liming.student.manager.data.model.StudentEntity"> UPDATE STUDENT_TBL <set> <if test="studentName != null and studentName != '' "> STUDENT_TBL.STUDENT_NAME = #{studentName}, </if> <if test="studentSex != null and studentSex != '' "> STUDENT_TBL.STUDENT_SEX = #{studentSex}, </if> <if test="studentBirthday != null "> STUDENT_TBL.STUDENT_BIRTHDAY = #{studentBirthday}, </if> <if test="studentPhoto != null "> STUDENT_TBL.STUDENT_PHOTO = #{studentPhoto, javaType=byte[], jdbcType=BLOB, typeHandler=org.apache.ibatis.type.BlobTypeHandler}, </if> <if test="classId != '' "> STUDENT_TBL.CLASS_ID = #{classId} </if> <if test="placeId != '' "> STUDENT_TBL.PLACE_ID = #{placeId} </if> </set> WHERE STUDENT_TBL.STUDENT_ID = #{studentId}; </update>

3.5 if + trim代替where/set標籤

       trim是更靈活的去處多餘關鍵字的標籤,他能夠實踐whereset的效果。

 

3.5.1trim代替where

<!-- 5.1 if/trim代替where(判斷參數) - 將實體類不爲空的屬性做爲where條件 --> <select id="getStudentList_if_trim" resultMap="resultMap_studentEntity"> SELECT ST.STUDENT_ID, ST.STUDENT_NAME, ST.STUDENT_SEX, ST.STUDENT_BIRTHDAY, ST.STUDENT_PHOTO, ST.CLASS_ID, ST.PLACE_ID FROM STUDENT_TBL ST <trim prefix="WHERE" prefixOverrides="AND|OR"> <if test="studentName !=null "> ST.STUDENT_NAME LIKE CONCAT(CONCAT('%', #{studentName, jdbcType=VARCHAR}),'%') </if> <if test="studentSex != null and studentSex != '' "> AND ST.STUDENT_SEX = #{studentSex, jdbcType=INTEGER} </if> <if test="studentBirthday != null "> AND ST.STUDENT_BIRTHDAY = #{studentBirthday, jdbcType=DATE} </if> <if test="classId != null and classId!= '' "> AND ST.CLASS_ID = #{classId, jdbcType=VARCHAR} </if> <if test="classEntity != null and classEntity.classId !=null and classEntity.classId !=' ' "> AND ST.CLASS_ID = #{classEntity.classId, jdbcType=VARCHAR} </if> <if test="placeId != null and placeId != '' "> AND ST.PLACE_ID = #{placeId, jdbcType=VARCHAR} </if> <if test="placeEntity != null and placeEntity.placeId != null and placeEntity.placeId != '' "> AND ST.PLACE_ID = #{placeEntity.placeId, jdbcType=VARCHAR} </if> <if test="studentId != null and studentId != '' "> AND ST.STUDENT_ID = #{studentId, jdbcType=VARCHAR} </if> </trim> </select>

 

3.5.2 trim代替set

<!-- 5.2 if/trim代替set(判斷參數) - 將實體類不爲空的屬性更新 --> <update id="updateStudent_if_trim" parameterType="liming.student.manager.data.model.StudentEntity"> UPDATE STUDENT_TBL <trim prefix="SET" suffixOverrides=","> <if test="studentName != null and studentName != '' "> STUDENT_TBL.STUDENT_NAME = #{studentName}, </if> <if test="studentSex != null and studentSex != '' "> STUDENT_TBL.STUDENT_SEX = #{studentSex}, </if> <if test="studentBirthday != null "> STUDENT_TBL.STUDENT_BIRTHDAY = #{studentBirthday}, </if> <if test="studentPhoto != null "> STUDENT_TBL.STUDENT_PHOTO = #{studentPhoto, javaType=byte[], jdbcType=BLOB, typeHandler=org.apache.ibatis.type.BlobTypeHandler}, </if> <if test="classId != '' "> STUDENT_TBL.CLASS_ID = #{classId}, </if> <if test="placeId != '' "> STUDENT_TBL.PLACE_ID = #{placeId} </if> </trim> WHERE STUDENT_TBL.STUDENT_ID = #{studentId} </update>

3.6 choose (when, otherwise)

 

    有時候咱們並不想應用全部的條件,而只是想從多個選項中選擇一個。而使用if標籤時,只要test中的表達式爲true,就會執行if標籤中的條件。 MyBatis提供了choose 元素。if標籤是與(and)的關係,而choose比傲天是或(or)的關係。

    choose標籤是按順序判斷其內部when標籤中的test條件出否成立,若是有一個成立,則choose結束。當choose中全部when的條件都 不滿則時,則執行otherwise中的sql。相似於Java 的switch 語句,choose爲switch,when爲case,otherwise則爲default。

    例以下面例子,一樣把全部能夠限制的條件都寫上,方面使用。choose會從上到下選擇一個when標籤的test爲true的sql執行。安全考慮,咱們使用where將choose包起來,放置關鍵字多於錯誤。

<!-- 6 choose(判斷參數) - 按順序將實體類第一個不爲空的屬性做爲where條件 --> <select id="getStudentList_choose" resultMap="resultMap_studentEntity" parameterType="liming.student.manager.data.model.StudentEntity"> SELECT ST.STUDENT_ID, ST.STUDENT_NAME, ST.STUDENT_SEX, ST.STUDENT_BIRTHDAY, ST.STUDENT_PHOTO, ST.CLASS_ID, ST.PLACE_ID FROM STUDENT_TBL ST <where> <choose> <when test="studentName !=null "> ST.STUDENT_NAME LIKE CONCAT(CONCAT('%', #{studentName, jdbcType=VARCHAR}),'%') </when > <when test="studentSex != null and studentSex != '' "> AND ST.STUDENT_SEX = #{studentSex, jdbcType=INTEGER} </when > <when test="studentBirthday != null "> AND ST.STUDENT_BIRTHDAY = #{studentBirthday, jdbcType=DATE} </when > <when test="classId != null and classId!= '' "> AND ST.CLASS_ID = #{classId, jdbcType=VARCHAR} </when > <when test="classEntity != null and classEntity.classId !=null and classEntity.classId !=' ' "> AND ST.CLASS_ID = #{classEntity.classId, jdbcType=VARCHAR} </when > <when test="placeId != null and placeId != '' "> AND ST.PLACE_ID = #{placeId, jdbcType=VARCHAR} </when > <when test="placeEntity != null and placeEntity.placeId != null and placeEntity.placeId != '' "> AND ST.PLACE_ID = #{placeEntity.placeId, jdbcType=VARCHAR} </when > <when test="studentId != null and studentId != '' "> AND ST.STUDENT_ID = #{studentId, jdbcType=VARCHAR} </when > <otherwise> </otherwise> </choose> </where> </select>

3.7 foreach

對於動態SQL 很是必須的,主是要迭代一個集合,一般是用於IN 條件。List 實例將使用「list」作爲鍵,數組實例以「array 作爲鍵。

foreach元素是很是強大的,它容許你指定一個集合,聲明集合項和索引變量,它們能夠用在元素體內。它也容許你指定開放和關閉的字符串,在迭代之間放置分隔符。這個元素是很智能的,它不會偶然地附加多餘的分隔符。

注意:你能夠傳遞一個List實例或者數組做爲參數對象傳給MyBatis。當你這麼作的時候,MyBatis會自動將它包裝在一個Map中,用名稱在做爲鍵。List實例將會以「list」做爲鍵,而數組實例將會以「array」做爲鍵。

這個部分是對關於XML配置文件和XML映射文件的而討論的。下一部分將詳細討論Java API,因此你能夠獲得你已經建立的最有效的映射。

 

 

3.7.1參數爲array示例的寫法

 

接口的方法聲明:

public List<StudentEntity> getStudentListByClassIds_foreach_array(String[] classIds);

動態SQL語句:

<!— 7.1 foreach(循環array參數) - 做爲where中in的條件 --> <select id="getStudentListByClassIds_foreach_array" resultMap="resultMap_studentEntity"> SELECT ST.STUDENT_ID, ST.STUDENT_NAME, ST.STUDENT_SEX, ST.STUDENT_BIRTHDAY, ST.STUDENT_PHOTO, ST.CLASS_ID, ST.PLACE_ID FROM STUDENT_TBL ST WHERE ST.CLASS_ID IN <foreach collection="array" item="classIds" open="(" separator="," close=")"> #{classIds} </foreach> </select>

測試代碼,查詢學生中,在2000000120000002這兩個班級的學生:

@Test public void test7_foreach() { String[] classIds = { "20000001", "20000002" }; List<StudentEntity> list = this.dynamicSqlMapper.getStudentListByClassIds_foreach_array(classIds); for (StudentEntity e : list) { System.out.println(e.toString()); } <p>}<span style="font-size: 14px; font-weight: bold; white-space: normal;">&nbsp;&nbsp;</span></p>
相關文章
相關標籤/搜索