日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 运维知识 > 数据库 >内容正文

数据库

MyBatis——动态SQL讲解

發布時間:2025/1/21 数据库 45 豆豆
生活随笔 收集整理的這篇文章主要介紹了 MyBatis——动态SQL讲解 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

MyBatis的動態SQL是基于OGNL表達式的,它可以幫助我們方便的在SQL語句中實現某些邏輯。?
MyBatis
中用于實現動態SQL的元素主要有:

  • if
  • where
  • set
  • choosewhenotherwise
  • trim
  • foreach

1、if標簽

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

<!-- 查詢學生listlike姓名 -->

<select id="getStudentListLikeName" parameterType="StudentEntity" resultMap="studentResultMap">

SELECT * from STUDENT_TBL ST

WHERE ST.STUDENT_NAME LIKE CONCAT(CONCAT('%', #{studentName}),'%')

</select>

但是此時如果studentNamenull,此語句很可能報錯或查詢結果為空。此時我們使用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());

}

}

2、if + where 的條件判斷

where中的條件使用的if標簽較多時,這樣的組合可能會導致錯誤。我們以在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、if + set 的更新語句

update語句中沒有使用if標簽時,如果有一個參數為null,都會導致錯誤。?
當在update語句中使用if標簽時,如果前面的if沒有執行,則或導致逗號多余錯誤。使用set標簽可以將動態的配置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>

4、choose (when, otherwise)

有時候我們并不想應用所有的條件,而只是想從多個選項中選擇一個。而使用if標簽時,只要test中的表達式為true,就會執行if標簽中的條件。MyBatis提供了choose 元素。if標簽是與(and)的關系,而choose標簽是或(or)的關系。

choose標簽是按順序判斷其內部when標簽中的test條件出否成立,如果有一個成立,則choose結束。choose中所有when的條件都不滿則時,則執行otherwise中的sql。類似于Java switch 語句,chooseswitchwhencaseotherwise則為default

例如下面例子,同樣把所有可以限制的條件都寫上,方面使用。choose會從上到下選擇一個when標簽的testtruesql執行。安全考慮,我們使用wherechoose包起來,放置關鍵字多于錯誤。

<!-- 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>

5、trim標簽

trim元素的主要功能是可以在自己包含的內容前加上某些前綴,也可以在其后加上某些后綴,與之對應的屬性是prefixsuffix;可以把包含內容的首部某些內容覆蓋,即忽略,也可以把尾部的某些內容覆蓋,對應的屬性是prefixOverridessuffixOverrides。正因為trim有這樣的功能,所以我們也可以非常簡單的利用trim來代替where/set標簽的功能,示例代碼如下:

trim代替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>

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>

6、foreach標簽

foreach的主要用在構建in條件中,它可以在SQL語句中進行迭代一個集合。foreach元素的屬性主要有itemindexcollectionopenseparatorclose

  • item表示集合中每一個元素進行迭代時的別名;
  • index指定一個名字,用于表示在迭代過程中,每次迭代到的位置;
  • open表示該語句以什么開始;
  • separator表示在每次進行迭代之間以什么符號作為分隔符;
  • close表示以什么結束;
  • 在使用foreach的時候最關鍵的也是最容易出錯的就是collection屬性,該屬性是必須指定的,但是在不同情況下,該屬性的值是不一樣的,主要有一下3種情況:?
    • 如果傳入的是單參數且參數類型是一個List的時候,collection屬性值為list
    • 如果傳入的是單參數且參數類型是一個array數組的時候,collection的屬性值為array
    • 如果傳入的參數是多個的時候,我們就需要把它們封裝成一個Map了,當然單參數也可以封裝成map,實際上如果你在傳入參數的時候,在MyBatis里面也是會把它封裝成一個Map的,mapkey就是參數名,所以這個時候collection屬性值就是傳入的Listarray對象在自己封裝的map里面的key

下面分別來看看上述三種情況的示例代碼:

1)單參數List的類型:

<select id="dynamicForeachTest" resultType="Blog">

select * from t_blog where id in

<foreach collection="list" index="index" item="item" open="(" separator="," close=")">

#{item}

</foreach>

</select>

上述collection的值為list,對應的Mapper是這樣的:

public List<Blog> dynamicForeachTest(List<Integer> ids);

測試代碼:

@Test

public void dynamicForeachTest() {

SqlSession session = Util.getSqlSessionFactory().openSession();

BlogMapper blogMapper = session.getMapper(BlogMapper.class);

List<Integer> ids = new ArrayList<Integer>();

ids.add(1);

ids.add(3);

ids.add(6);

List<Blog> blogs = blogMapper.dynamicForeachTest(ids);

for (Blog blog : blogs)

System.out.println(blog);

session.close();

}

2)單參數array數組的類型:

<select id="dynamicForeach2Test" resultType="Blog">

select * from t_blog where id in

<foreach collection="array" index="index" item="item" open="(" separator="," close=")">

#{item}

</foreach>

</select>

上述collectionarray,對應的Mapper代碼:

public List<Blog> dynamicForeach2Test(int[] ids);

測試代碼:

@Test

public void dynamicForeach2Test() {

SqlSession session = Util.getSqlSessionFactory().openSession();

BlogMapper blogMapper = session.getMapper(BlogMapper.class);

int[] ids = new int[] {1,3,6,9};

List<Blog> blogs = blogMapper.dynamicForeach2Test(ids);

for (Blog blog : blogs)

System.out.println(blog);

session.close();

}

3)自己把參數封裝成Map的類型

<select id="dynamicForeach3Test" resultType="Blog">

select * from t_blog where title like "%"#{title}"%" and id in

<foreach collection="ids" index="index" item="item" open="(" separator="," close=")">

#{item}

</foreach>

</select>

上述collection的值為ids,是傳入的參數Mapkey,對應的Mapper代碼:

public List<Blog> dynamicForeach3Test(Map<String, Object> params);

測試代碼:

@Test

public void dynamicForeach3Test() {

SqlSession session = Util.getSqlSessionFactory().openSession();

BlogMapper blogMapper = session.getMapper(BlogMapper.class);

final List<Integer> ids = new ArrayList<Integer>();

ids.add(1);

ids.add(2);

ids.add(3);

ids.add(6);

ids.add(7);

ids.add(9);

Map<String, Object> params = new HashMap<String, Object>();

params.put("ids", ids);

params.put("title", "中國");

List<Blog> blogs = blogMapper.dynamicForeach3Test(params);

for (Blog blog : blogs)

System.out.println(blog);

session.close();

}

轉載:http://haohaoxuexi.iteye.com/blog/1338557?

總結

以上是生活随笔為你收集整理的MyBatis——动态SQL讲解的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。