MyBatis學習 之 一、MyBatis簡介與配置MyBatis+Spring+MySql
MyBatis學習 之 二、SQL語句映射文件(1)resultMap
MyBatis學習 之 二、SQL語句映射文件(2)增刪改查、參數、緩存
有些時候,sql語句where條件中,需要一些安全判斷,例如按某一條件查詢時如果傳入的參數是空,此時查詢出的結果很可能是空的,也許我們需要參數為空時,是查出全部的信息。使用Oracle的序列、mysql的函數生成Id。這時我們可以使用動態sql。
下文均采用mysql語法和函數(例如字符串鏈接函數CONCAT)。
3.1 selectKey標簽
在insert語句中,在Oracle經常使用序列、在MySQL中使用函數來自動生成插入表的主鍵,而且需要方法能返回這個生成主鍵。使用myBatis的selectKey標簽可以實現這個效果。
下面例子,使用mysql數據庫自定義函數nextval('student'),用來生成一個key,并把他設置到傳入的實體類中的studentId屬性上。所以在執行完此方法后,邊可以通過這個實體類獲取生成的key。
- <!--插入學生自動主鍵-->
- < insert id = "createStudentAutoKey" parameterType = "liming.student.manager.data.model.StudentEntity" keyProperty = "studentId" >
- < selectKey keyProperty = "studentId" resultType = "String" order = "BEFORE" >
- selectnextval('student')
- </ selectKey >
- INSERTINTOSTUDENT_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
- StudentEntityentity= 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 |
1:BEFORE,會先選擇主鍵,然后設置keyProperty,再執行insert語句; 2:AFTER,就先運行insert語句再運行selectKey語句。 |
BEFORE AFTER |
statementType | MyBatis支持STATEMENT,PREPARED和CALLABLE的語句形式,對應Statement,PreparedStatement和CallableStatement響應 |
STATEMENT PREPARED CALLABLE |
3.2 if標簽
if標簽可用在許多類型的sql語句中,我們以查詢為例。首先看一個很普通的查詢:
- <!--查詢學生list,like姓名-->
- < select id = "getStudentListLikeName" parameterType = "StudentEntity" resultMap = "studentResultMap" >
- SELECT*fromSTUDENT_TBLST
- WHEREST.STUDENT_NAMELIKECONCAT(CONCAT('%',#{studentName}),'%')
- </ select >
但是此時如果studentName或studentSex為null,此語句很可能報錯或查詢結果為空。此時我們使用if動態sql語句先進行判斷,如果值為null或等于空字符串,我們就不進行此條件的判斷,增加靈活性。
參數為實體類StudentEntity。將實體類中所有的屬性均進行判斷,如果不為空則執行判斷條件。
- <!--2if(判斷參數)-將實體類不為空的屬性作為where條件-->
- < select id = "getStudentList_if" resultMap = "resultMap_studentEntity" parameterType = "liming.student.manager.data.model.StudentEntity" >
- SELECTST.STUDENT_ID,
- ST.STUDENT_NAME,
- ST.STUDENT_SEX,
- ST.STUDENT_BIRTHDAY,
- ST.STUDENT_PHOTO,
- ST.CLASS_ID,
- ST.PLACE_ID
- FROMSTUDENT_TBLST
- WHERE
- < if test = "studentName!=null" >
- ST.STUDENT_NAMELIKECONCAT(CONCAT('%',#{studentName, jdbcType = VARCHAR }),'%')
- </ if >
- < if test = "studentSex!=nullandstudentSex!=''" >
- AND ST.STUDENT_SEX =#{studentSex, jdbcType = INTEGER }
- </ if >
- < if test = "studentBirthday!=null" >
- AND ST.STUDENT_BIRTHDAY =#{studentBirthday, jdbcType = DATE }
- </ if >
- < if test = "classId!=nullandclassId!=''" >
- AND ST.CLASS_ID =#{classId, jdbcType = VARCHAR }
- </ if >
- < if test = "classEntity!=nullandclassEntity.classId!=nullandclassEntity.classId!=''" >
- AND ST.CLASS_ID =#{classEntity.classId, jdbcType = VARCHAR }
- </ if >
- < if test = "placeId!=nullandplaceId!=''" >
- AND ST.PLACE_ID =#{placeId, jdbcType = VARCHAR }
- </ if >
- < if test = "placeEntity!=nullandplaceEntity.placeId!=nullandplaceEntity.placeId!=''" >
- AND ST.PLACE_ID =#{placeEntity.placeId, jdbcType = VARCHAR }
- </ if >
- < if test = "studentId!=nullandstudentId!=''" >
- AND ST.STUDENT_ID =#{studentId, jdbcType = VARCHAR }
- </ if >
- </ select >
使用時比較靈活,new一個這樣的實體類,我們需要限制那個條件,只需要附上相應的值就會where這個條件,相反不去賦值就可以不在where中判斷。
- public void select_test_2_1(){
- StudentEntityentity= 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 (StudentEntitye:list){
- System.out.println(e.toString());
- }
- }
3.3 if + where的條件判斷
當where中的條件使用的if標簽較多時,這樣的組合可能會導致錯誤。我們以在3.1中的查詢語句為例子,當java代碼按如下方法調用時:
- @Test
- public void select_test_2_1(){
- StudentEntityentity= new StudentEntity();
- entity.setStudentName( null );
- entity.setStudentSex( 1 );
- List<StudentEntity>list= this .dynamicSqlMapper.getStudentList_if(entity);
- for (StudentEntitye:list){
- System.out.println(e.toString());
- }
- }
如果上面例子,參數studentName為null,將不會進行STUDENT_NAME列的判斷,則會直接導“WHERE AND”關鍵字多余的錯誤SQL。
這時我們可以使用where動態語句來解決。這個“where”標簽會知道如果它包含的標簽中有返回值的話,它就插入一個‘where’。此外,如果標簽返回的內容是以AND或OR開頭的,則它會剔除掉。
上面例子修改為:
- <!--3select-where/if(判斷參數)-將實體類不為空的屬性作為where條件-->
- < select id = "getStudentList_whereIf" resultMap = "resultMap_studentEntity" parameterType = "liming.student.manager.data.model.StudentEntity" >
- SELECTST.STUDENT_ID,
- ST.STUDENT_NAME,
- ST.STUDENT_SEX,
- ST.STUDENT_BIRTHDAY,
- ST.STUDENT_PHOTO,
- ST.CLASS_ID,
- ST.PLACE_ID
- FROMSTUDENT_TBLST
- < where >
- < if test = "studentName!=null" >
- ST.STUDENT_NAMELIKECONCAT(CONCAT('%',#{studentName, jdbcType = VARCHAR }),'%')
- </ if >
- < if test = "studentSex!=nullandstudentSex!=''" >
- AND ST.STUDENT_SEX =#{studentSex, jdbcType = INTEGER }
- </ if >
- < if test = "studentBirthday!=null" >
- AND ST.STUDENT_BIRTHDAY =#{studentBirthday, jdbcType = DATE }
- </ if >
- < if test = "classId!=nullandclassId!=''" >
- AND ST.CLASS_ID =#{classId, jdbcType = VARCHAR }
- </ if >
- < if test = "classEntity!=nullandclassEntity.classId!=nullandclassEntity.classId!=''" >
- AND ST.CLASS_ID =#{classEntity.classId, jdbcType = VARCHAR }
- </ if >
- < if test = "placeId!=nullandplaceId!=''" >
- AND ST.PLACE_ID =#{placeId, jdbcType = VARCHAR }
- </ if >
- < if test = "placeEntity!=nullandplaceEntity.placeId!=nullandplaceEntity.placeId!=''" >
- AND ST.PLACE_ID =#{placeEntity.placeId, jdbcType = VARCHAR }
- </ if >
- < if test = "studentId!=nullandstudentId!=''" >
- 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則不進行更新,而是保持數據庫原值。如下示例:
- <!--4if/set(判斷參數)-將實體類不為空的屬性更新-->
- < update id = "updateStudent_if_set" parameterType = "liming.student.manager.data.model.StudentEntity" >
- UPDATESTUDENT_TBL
- < set >
- < if test = "studentName!=nullandstudentName!=''" >
- STUDENT_TBL.STUDENT_NAME =#{studentName},
- </ if >
- < if test = "studentSex!=nullandstudentSex!=''" >
- 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是更靈活的去處多余關鍵字的標簽,他可以實踐where和set的效果。
3.5.1trim代替where
- <!--5.1if/trim代替where(判斷參數)-將實體類不為空的屬性作為where條件-->
- < select id = "getStudentList_if_trim" resultMap = "resultMap_studentEntity" >
- SELECTST.STUDENT_ID,
- ST.STUDENT_NAME,
- ST.STUDENT_SEX,
- ST.STUDENT_BIRTHDAY,
- ST.STUDENT_PHOTO,
- ST.CLASS_ID,
- ST.PLACE_ID
- FROMSTUDENT_TBLST
- < trim prefix = "WHERE" prefixOverrides = "AND|OR" >
- < if test = "studentName!=null" >
- ST.STUDENT_NAMELIKECONCAT(CONCAT('%',#{studentName, jdbcType = VARCHAR }),'%')
- </ if >
- < if test = "studentSex!=nullandstudentSex!=''" >
- AND ST.STUDENT_SEX =#{studentSex, jdbcType = INTEGER }
- </ if >
- < if test = "studentBirthday!=null" >
- AND ST.STUDENT_BIRTHDAY =#{studentBirthday, jdbcType = DATE }
- </ if >
- < if test = "classId!=nullandclassId!=''" >
- AND ST.CLASS_ID =#{classId, jdbcType = VARCHAR }
- </ if >
- < if test = "classEntity!=nullandclassEntity.classId!=nullandclassEntity.classId!=''" >
- AND ST.CLASS_ID =#{classEntity.classId, jdbcType = VARCHAR }
- </ if >
- < if test = "placeId!=nullandplaceId!=''" >
- AND ST.PLACE_ID =#{placeId, jdbcType = VARCHAR }
- </ if >
- < if test = "placeEntity!=nullandplaceEntity.placeId!=nullandplaceEntity.placeId!=''" >
- AND ST.PLACE_ID =#{placeEntity.placeId, jdbcType = VARCHAR }
- </ if >
- < if test = "studentId!=nullandstudentId!=''" >
- AND ST.STUDENT_ID =#{studentId, jdbcType = VARCHAR }
- </ if >
- </ trim >
- </ select >
3.5.2 trim代替set
- <!--5.2if/trim代替set(判斷參數)-將實體類不為空的屬性更新-->
- < update id = "updateStudent_if_trim" parameterType = "liming.student.manager.data.model.StudentEntity" >
- UPDATESTUDENT_TBL
- < trim prefix = "SET" suffixOverrides = "," >
- < if test = "studentName!=nullandstudentName!=''" >
- STUDENT_TBL.STUDENT_NAME =#{studentName},
- </ if >
- < if test = "studentSex!=nullandstudentSex!=''" >
- 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包起來,放置關鍵字多于錯誤。
- <!--6choose(判斷參數)-按順序將實體類第一個不為空的屬性作為where條件-->
- < select id = "getStudentList_choose" resultMap = "resultMap_studentEntity" parameterType = "liming.student.manager.data.model.StudentEntity" >
- SELECTST.STUDENT_ID,
- ST.STUDENT_NAME,
- ST.STUDENT_SEX,
- ST.STUDENT_BIRTHDAY,
- ST.STUDENT_PHOTO,
- ST.CLASS_ID,
- ST.PLACE_ID
- FROMSTUDENT_TBLST
- < where >
- < choose >
- < when test = "studentName!=null" >
- ST.STUDENT_NAMELIKECONCAT(CONCAT('%',#{studentName, jdbcType = VARCHAR }),'%')
- </ when >
- < when test = "studentSex!=nullandstudentSex!=''" >
- AND ST.STUDENT_SEX =#{studentSex, jdbcType = INTEGER }
- </ when >
- < when test = "studentBirthday!=null" >
- AND ST.STUDENT_BIRTHDAY =#{studentBirthday, jdbcType = DATE }
- </ when >
- < when test = "classId!=nullandclassId!=''" >
- AND ST.CLASS_ID =#{classId, jdbcType = VARCHAR }
- </ when >
- < when test = "classEntity!=nullandclassEntity.classId!=nullandclassEntity.classId!=''" >
- AND ST.CLASS_ID =#{classEntity.classId, jdbcType = VARCHAR }
- </ when >
- < when test = "placeId!=nullandplaceId!=''" >
- AND ST.PLACE_ID =#{placeId, jdbcType = VARCHAR }
- </ when >
- < when test = "placeEntity!=nullandplaceEntity.placeId!=nullandplaceEntity.placeId!=''" >
- AND ST.PLACE_ID =#{placeEntity.placeId, jdbcType = VARCHAR }
- </ when >
- < when test = "studentId!=nullandstudentId!=''" >
- 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示例的寫法
接口的方法聲明:
動態SQL語句:
- <!—7.1foreach(循環array參數)-作為where中in的條件-- >
- < select id = "getStudentListByClassIds_foreach_array" resultMap = "resultMap_studentEntity" >
- SELECTST.STUDENT_ID,
- ST.STUDENT_NAME,
- ST.STUDENT_SEX,
- ST.STUDENT_BIRTHDAY,
- ST.STUDENT_PHOTO,
- ST.CLASS_ID,
- ST.PLACE_ID
- FROMSTUDENT_TBLST
- WHEREST.CLASS_IDIN
- < foreach collection = "array" item = "classIds" open = "(" separator = "," close = ")" >
- #{classIds}
- </ foreach >
- </ select >
測試代碼,查詢學生中,在20000001、20000002這兩個班級的學生:
- @Test
- public void test7_foreach(){
- String[]classIds={ "20000001" , "20000002" };
- List<StudentEntity>list= this .dynamicSqlMapper.getStudentListByClassIds_foreach_array(classIds);
- for (StudentEntitye:list){
- System.out.println(e.toString());
- }
- <p>}<spanstyle= "font-size:14px;font-weight:bold;white-space:normal;" ></span></p>
3.7.2參數為list示例的寫法
接口的方法聲明:
動態SQL語句:
- <!--7.2foreach(循環List<String>參數)-作為where中in的條件-->
- < select id = "getStudentListByClassIds_foreach_list" resultMap = "resultMap_studentEntity" >
- SELECTST.STUDENT_ID,
- ST.STUDENT_NAME,
- ST.STUDENT_SEX,
- ST.STUDENT_BIRTHDAY,
- ST.STUDENT_PHOTO,
- ST.CLASS_ID,
- ST.PLACE_ID
- FROMSTUDENT_TBLST
- WHEREST.CLASS_IDIN
- < foreach collection = "list" item = "classIdList" open = "(" separator = "," close = ")" >
- #{classIdList}
- </ foreach >
- </ select >
測試代碼,查詢學生中,在20000001、20000002這兩個班級的學生:
- @Test
- public void test7_2_foreach(){
- ArrayList<String>classIdList= new ArrayList<String>();
- classIdList.add( "20000001" );
- classIdList.add( "20000002" );
- List<StudentEntity>list= this .dynamicSqlMapper.getStudentListByClassIds_foreach_list(classIdList);
- for (StudentEntitye:list){
- System.out.println(e.toString());
- }
- }
MyBatis學習 之 一、MyBatis簡介與配置MyBatis+Spring+MySql
MyBatis學習 之 二、SQL語句映射文件(1)resultMap
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
