Mybatis中Mapper標(biāo)簽總結(jié)大全
一、標(biāo)簽分類(lèi)
定義SQL語(yǔ)句
- insert
- delete
- update
- select
配置關(guān)聯(lián)關(guān)系
- collection
- association
配置java對(duì)象屬性與查詢(xún)結(jié)果集中列名的對(duì)應(yīng)關(guān)系
- resultMap
控制動(dòng)態(tài)SQL拼接
- foreach
- if
- choose
格式化輸出
- where
- set
- trim
定義常量
- sql
其他
- include
二、標(biāo)簽總結(jié)
1. 基礎(chǔ)SQL標(biāo)簽
1.1 查詢(xún)select
標(biāo)簽屬性
- id 唯一的名稱(chēng),對(duì)應(yīng)dao中mapper的接口名稱(chēng)
- paramterType 定義傳入的參數(shù)類(lèi)型
- resultType 返回?cái)?shù)據(jù)類(lèi)型對(duì)應(yīng)實(shí)體類(lèi)
- resultMap 外部 resultMap 的命名引用。結(jié)果集的映射是 MyBatis 最強(qiáng)大的特性,對(duì)其有一個(gè)很好的理解的話(huà),許多復(fù)雜映射的情形都能迎刃而解。使用 resultMap 或 resultType,但不能同時(shí)使用
- flushCache 將其設(shè)置為 true,任何時(shí)候只要語(yǔ)句被調(diào)用,都會(huì)導(dǎo)致本地緩存和二級(jí)緩存都會(huì)被清空,默認(rèn)值:false
- useCache 將其設(shè)置為 true,將會(huì)導(dǎo)致本條語(yǔ)句的結(jié)果被二級(jí)緩存,默認(rèn)值:對(duì) select 元素為 true
- timeout 這個(gè)設(shè)置是在拋出異常之前,驅(qū)動(dòng)程序等待數(shù)據(jù)庫(kù)返回請(qǐng)求結(jié)果的秒數(shù)。默認(rèn)值為 unset(依賴(lài)驅(qū)動(dòng))
- fetchSize 這是嘗試影響驅(qū)動(dòng)程序每次批量返回的結(jié)果行數(shù)和這個(gè)設(shè)置值相等。默認(rèn)值為 unset(依賴(lài)驅(qū)動(dòng))。
- statementType STATEMENT,PREPARED 或 CALLABLE 的一個(gè)。這會(huì)讓 MyBatis 分別使用 Statement,PreparedStatement 或 CallableStatement,默認(rèn)值:PREPARED。
- resultSetType FORWARD_ONLY,SCROLL_SENSITIVE 或 SCROLL_INSENSITIVE 中的一個(gè),默認(rèn)值為 unset (依賴(lài)驅(qū)動(dòng))。
- databaseId 如果配置了 databaseIdProvider,MyBatis 會(huì)加載所有的不帶 databaseId 或匹配當(dāng)前 databaseId 的語(yǔ)句;如果帶或者不帶的語(yǔ)句都有,則不帶的會(huì)被忽略。
- resultOrdered 這個(gè)設(shè)置僅針對(duì)嵌套結(jié)果 select 語(yǔ)句適用:如果為true,就是假設(shè)包含了嵌套結(jié)果集或是分組了,這樣的話(huà)當(dāng)返回一個(gè)主結(jié)果行的時(shí)候,就不會(huì)發(fā)生有對(duì)前面結(jié)果集的引用的情況。這就使得在獲取嵌套的結(jié)果集的時(shí)候不至導(dǎo)致內(nèi)存不夠用。默認(rèn)值:false。
- resultSets 這個(gè)設(shè)置僅對(duì)多結(jié)果集的情況適用,它將列出語(yǔ)句執(zhí)行后返回的結(jié)果集并每個(gè)結(jié)果集給一個(gè)名稱(chēng),名稱(chēng)是逗號(hào)分隔的。
/**
* 根據(jù)條件查詢(xún)用戶(hù)集合
*/
List<User> selectUsers(@Param("cond")Map<String, Object> map);
<!-- 返回的是List,resultType給定的值是List里面的實(shí)體類(lèi)而不是list,mybatis會(huì)自動(dòng)把結(jié)果變成List -->
<select id="selectUsers" parameterType="map" resultType="con.it.bean.User">
select id, username, password, sex, birthday, address from user u
<where>
<trim suffixOverrides=",">
<if test="cond.username != null and cond.username != ''">
u.username = #{cond.username},
</if>
<if test="cond.sex != null">
and u.sex = #{cond.sex},
</if>
<if test="cond.beginTime != null">
<![CDATA[ and DATE_FORMAT(u.birthday, '%Y-%m-%d %H:%T:%s') >= DATE_FORMAT(#{beginTime}, '%Y-%m-%d %H:%T:%s'), ]]>
</if>
<if test="cond.endTime != null">
<![CDATA[ and DATE_FORMAT(u.birthday, '%Y-%m-%d %H:%T:%s') <= DATE_FORMAT(#{endTime}, '%Y-%m-%d %H:%T:%s'), ]]>
</if>
<if test="cond.address != null and cond.address != ''">
and u.addrerss like '%' || #{cond.address} || '%',
</if>
</trim>
</where>
</select>
1.2 增刪改
標(biāo)簽屬性
- id 唯一的名稱(chēng),對(duì)應(yīng)dao中mapper的接口名稱(chēng)
- parameterType 將要傳入語(yǔ)句的參數(shù)的完全限定類(lèi)名或別名。這個(gè)屬性是可選的,因?yàn)?MyBatis 可以通過(guò) TypeHandler 推斷出具體傳入語(yǔ)句的參數(shù),默認(rèn)值為 unset。
- flushCache 將其設(shè)置為 true,任何時(shí)候只要語(yǔ)句被調(diào)用,都會(huì)導(dǎo)致本地緩存和二級(jí)緩存都會(huì)被清空,默認(rèn)值:true(對(duì)應(yīng)插入、更新和刪除語(yǔ)句)。
- timeout 這個(gè)設(shè)置是在拋出異常之前,驅(qū)動(dòng)程序等待數(shù)據(jù)庫(kù)返回請(qǐng)求結(jié)果的秒數(shù)。默認(rèn)值為 unset(依賴(lài)驅(qū)動(dòng))。
- statementType STATEMENT,PREPARED 或 CALLABLE 的一個(gè)。這會(huì)讓 MyBatis 分別使用 Statement,PreparedStatement 或 CallableStatement,默認(rèn)值:PREPARED。
- useGeneratedKeys(僅對(duì) insert 和 update 有用)這會(huì)令 MyBatis 使用 JDBC 的 getGeneratedKeys 方法來(lái)取出由數(shù)據(jù)庫(kù)內(nèi)部生成的主鍵(比如:像 MySQL 和 SQL Server這樣的關(guān)系數(shù)據(jù)庫(kù)管理系統(tǒng)的自動(dòng)遞增字段, oracle使用序列是不支持的,通過(guò)selectKey可以返回主鍵),默認(rèn)值:false。
- keyProperty (僅對(duì) insert 和 update 有用)唯一標(biāo)記一個(gè)屬性,MyBatis 會(huì)通過(guò) getGeneratedKeys 的返回值或者通過(guò) insert 語(yǔ)句的 selectKey子元素設(shè)置它的鍵值,默認(rèn):unset。如果希望得到多個(gè)生成的列,也可以是逗號(hào)分隔的屬性名稱(chēng)列表。
- keyColumn(僅對(duì) insert 和 update 有用)通過(guò)生成的鍵值設(shè)置表中的列名,這個(gè)設(shè)置僅在某些數(shù)據(jù)庫(kù)(像PostgreSQL)是必須的,當(dāng)主鍵列不是表中的第一列的時(shí)候需要設(shè)置。如果希望得到多個(gè)生成的列,也可以是逗號(hào)分隔的屬性名稱(chēng)列表。
- databaseId 如果配置了 databaseIdProvider,MyBatis 會(huì)加載所有的不帶 databaseId 或匹配當(dāng)前 databaseId 的語(yǔ)句;如果帶或者不帶的語(yǔ)句都有,則不帶的會(huì)被忽略。
<insert id="insert" parameterType="com.it.bean.User">
<!-- 使用序列插入oracle數(shù)據(jù)庫(kù)返回主鍵,MYSQL數(shù)據(jù)庫(kù)無(wú)需添加selectKey -->
<selectKey resultType="long" order="BEFORE" keyProperty="id">
SELECT user_seq.NEXTVAL as id from DUAL
</selectKey>
insert into User (ID, USERNAME, PASSWORD, SEX, ADRESS, CREATED_BY, CREADTED_DATE)
values (#{id}, #{username}, #{password}, #{sex}, #{adress}, #{createdBy}, SYSDATE)
</insert>
1.3 其他基礎(chǔ)標(biāo)簽
1.3.1 sql 標(biāo)簽
定義一些常用的sql語(yǔ)句片段
<sql id="selectParam"> id, username, password, sex, birthday, address </sql>
1.3.2 include 標(biāo)簽
引用其他的常量,通常和sql一起使用
<select> select <include refid="selectParam"></include> from user </select>
1.3.3 if 標(biāo)簽
基本都是用來(lái)判斷值是否為空,注意Integer的判斷,mybatis會(huì)默認(rèn)把0變成 ‘'
<if test="item != null and item != ''"></if> <!-- 如果是Integer類(lèi)型的需要把a(bǔ)nd后面去掉或是加上or--> <if test="item != null"></if> <if test="item != null and item != '' or item == 0"></if>
1.3.4 別名
經(jīng)常使用的類(lèi)型可以定義別名,方便使用,mybatis也注冊(cè)了很多別名方便我們使用,詳情見(jiàn)底部附錄
<typeAliases> <typeAlias type="com.it.bean.User" alias="User"/> </typeAliases>
2. collection與association標(biāo)簽
collection與association的屬性一樣,都是用于resultMap返回關(guān)聯(lián)映射使用,collection關(guān)聯(lián)的是集合,而association是關(guān)聯(lián)單個(gè)對(duì)象
標(biāo)簽屬性
- property resultMap返回實(shí)體類(lèi)中字段和result標(biāo)簽中的property一樣
- column 數(shù)據(jù)庫(kù)的列名或者列標(biāo)簽別名,是關(guān)聯(lián)查詢(xún)往下一個(gè)語(yǔ)句傳送值。注意: 在處理組合鍵時(shí),您可以使用column=“{prop1=col1,prop2=col2}”這樣的語(yǔ)法,設(shè)置多個(gè)列名傳入到嵌套查詢(xún)語(yǔ)句。這就會(huì)把prop1和prop2設(shè)置到目標(biāo)嵌套選擇語(yǔ)句的參數(shù)對(duì)象中。
- javaType 一般為ArrayList或是java.util.List
- ofType java的實(shí)體類(lèi),對(duì)應(yīng)數(shù)據(jù)庫(kù)表的列名稱(chēng),即關(guān)聯(lián)查詢(xún)select對(duì)應(yīng)返回的類(lèi)
- select 執(zhí)行一個(gè)其他映射的sql語(yǔ)句返回一個(gè)java實(shí)體類(lèi)型
/**
*問(wèn)題表
*/
public class Question {
private Long id; //問(wèn)題id
private String question; //問(wèn)題
private Integer questionType; //問(wèn)題類(lèi)型
private List<QuestionAnswer> answerList; //問(wèn)題選項(xiàng)集合
//Getter和Setter省略
}
/**
*問(wèn)題選項(xiàng)表
*/
public class QuestionAnswer {
private Long id; //選項(xiàng)id
private Long questionId; //問(wèn)題id
private String answer; //選項(xiàng)
//Getter和Setter省略
}
<!-- 具體可參考下面ResultMap -->
<collection property="answerList" javaType="java.util.List"
ofType="com.it.bean.QuestionAnswer" column="id"
select="setlectQuestionAnswerByQuestionId"/>
3. resultMap標(biāo)簽
resultMap屬性
- id 唯一標(biāo)識(shí)
- type 返回類(lèi)型
- extends 繼承別的resultMap,可選
關(guān)聯(lián)其他標(biāo)簽
- id 設(shè)置主鍵使用,使用此標(biāo)簽配置映射關(guān)系(可能不止一個(gè))
- result 一般屬性的配置映射關(guān)系,一般不止一個(gè)
- association 關(guān)聯(lián)一個(gè)對(duì)象使用
- collection 關(guān)聯(lián)一個(gè)集合使用
<!-- 返回關(guān)聯(lián)查詢(xún)的問(wèn)題 -->
<resultMap id="detail_result" type="com.it.bean.Question">
<id column="id" property="id" />
<result column="question" property="question" />
<result column="question_type" property="questionType" />
<collection property="answerList" javaType="java.util.List"
ofType="com.it.bean.QuestionAnswer" column="id"
select="setlectQuestionAnswerByQuestionId"/>
</resultMap>
<!-- 查詢(xún)問(wèn)題集 -->
<select id="selectQuestions" parameterType="map" resultMap="detail_result">
select q.id, q.question, q.question_type
from question q
<where>
<if test="cond.id != null">
q.id = #{cond.id}
</if>
<if test="cond.idList != null and cond.idList.size() != 0">
q.id in
<foreach collection="cond.idList" item="id" open="(" separator="," close=")">
#{id}
</foreach>
</if>
</where>
</select>
<!-- 查詢(xún)對(duì)應(yīng)問(wèn)題的答案集 -->
<select id="setlectQuestionAnswerByQuestionId" parameterType="long" resultType="com.it.bean.QuestionAnswer">
select a.id, a.answer from question_answer a where a.question_id = #{id}
</select>
4. foreach標(biāo)簽
foreach屬性
- collection 循環(huán)的集合。傳的是集合為list,數(shù)組為array, 如果是map為java.util.HashMap
- item 循環(huán)的key
- index 循環(huán)的下表順序
- open 循環(huán)的開(kāi)頭
- close 循環(huán)結(jié)束
- separator 循環(huán)的分隔符
<sql id="base_column">id, question_id, answer</sql>
<!-- oracle的批量插入 -->
<insert id="insertBatchOracle" parameterType="list">
insert into question_answer ( <include refid="base_column" /> )
select question_answer_seq.NEXTVAL, A.* from (
<foreach collection="list" item="item" separator="union all">
select #{item.questionId}, #{item.answer} from dual
</foreach>
) A
</insert>
<!-- Mysql的批量插入,主鍵自增 -->
<insert id="insertBatchMysql" parameterType="list">
insert into question_answer ( <include refid="base_column" /> )
values
<foreach collection="list" item="item" open="(" separator="union all" close=")">
#{item.id}, #{item.questionId}, #{item.answer}
</foreach>
</insert>
5. where標(biāo)簽
where用來(lái)去掉多條件查詢(xún)時(shí),開(kāi)頭多余的and
<select id="selectUserList" parameterType="com.it.bean.User" resultType="com.it.bean.User">
<!-- 引用Sql片段 -->
select <include refid="selectParam"> from user u
<where>
<!--where 可以自動(dòng)去掉條件中的第一個(gè)and-->
<if test="id != null">
and u.id = #{id}
</if>
<if test="name != null and name != ''">
and u.name = #{name}
</if>
</where>
</select>
6. set標(biāo)簽
set是mybatis提供的一個(gè)智能標(biāo)記,當(dāng)在update語(yǔ)句中使用if標(biāo)簽時(shí),如果前面的if沒(méi)有執(zhí)行,則或?qū)е露禾?hào)多余錯(cuò)誤。使用set標(biāo)簽可以將動(dòng)態(tài)的配置SET 關(guān)鍵字,和剔除追加到條件末尾的任何不相關(guān)的逗號(hào)。
沒(méi)有使用if標(biāo)簽時(shí),如果有一個(gè)參數(shù)為null,都會(huì)導(dǎo)致錯(cuò)誤,如下示例:
<update id="updateUser" parameterType="com.it.bean.user">
update user
<set>
<if test="username != null and username != ''">
username = #{username},
</if>
<if test="sex != null and sex == 0 or sex == 1">
sex = #{sex},
</if>
<if test="birthday != null ">
birthday = #{birthday},
</if >
<if test="address != null and address != ''">
address = #{address},
</if>
<if test="lastModifiedBy != null and lastModifiedBy != ''">
last_modified_by = #{lastModifiedBy},
last_modified_date = SYSDATE,
</if>
</set>
<where>
id = #{id}
</where>
</update>
7. trim標(biāo)簽
trim標(biāo)記是一個(gè)格式化的標(biāo)記,可以完成set或者是where標(biāo)記的功能
標(biāo)簽屬性
- prefix、suffix 表示再trim標(biāo)簽包裹部分的前面或后面添加內(nèi)容(注意:是沒(méi)有prefixOverrides,suffixOverrides的情況下)
- prefixOverrides,suffixOverrides 表示覆蓋內(nèi)容,如果只有這兩個(gè)屬性表示刪除內(nèi)容
<update id="test" parameterType="com.it.bean.User">
update user
<!-- 開(kāi)頭加上set,結(jié)尾去除最后一個(gè)逗號(hào) -->
<trim prefix="set" suffixOverrides=",">
<if test="username!=null and username != ''">
name= #{username},
</if>
<if test="password!=null and password != ''">
password= #{password},
</if>
</trim>
<where>
id = #{id}
</where>
</update>
8. choose、when、otherwise標(biāo)簽
有時(shí)候我們并不想應(yīng)用所有的條件,而只是想從多個(gè)選項(xiàng)中選擇一個(gè)。MyBatis提供了choose 元素,按順序判斷when中的條件出否成立,如果有一個(gè)成立,則choose結(jié)束。當(dāng)choose中所有when的條件都不滿(mǎn)則時(shí),則執(zhí)行 otherwise中的sql。類(lèi)似于Java 的switch 語(yǔ)句,choose為switch,when為case,otherwise則為default。if是與(and)的關(guān)系,而choose是或(or)的關(guān)系
<select id="getUserList" resultType="com.it.bean.User" parameterType="com.it.bean.User">
SELECT <include refid="resultParam"></include> FROM User u
<where>
<choose>
<when test="username !=null and username != ''">
u.username LIKE CONCAT(CONCAT('%', #{username}),'%')
</when >
<when test="sex != null">
AND u.sex = #{sex}
</when >
<when test="birthday != null ">
AND u.birthday = #{birthday}
</when >
<otherwise>
</otherwise>
</choose>
</where>
</select>
附Mybatis已經(jīng)注冊(cè)好的別名表
| 別名 | 映射類(lèi)型 |
|---|---|
| _byte | byte |
| _long | long |
| _short | short |
| _int | int |
| _integer | int |
| _double | double |
| _float | float |
| _boolean | boolean |
| string | String |
| byte | Byte |
| long | Long |
| short | Short |
| int | Integer |
| integer | Integer |
| double | Double |
| float | Float |
| boolean | Boolean |
| date | Date |
| decimal | BigDecimal |
| bigdecimal | BigDecimal |
| map | Map |
| hashmap | HashMap |
| list | list |
| arraylist | ArrayList |
| collection | Collection |
| iterator | Iterator |
二、寫(xiě)在后面
在網(wǎng)上看了很多標(biāo)簽的解釋?zhuān)皇呛苋?,我就自己總結(jié)了一份,搭配示例更好理解標(biāo)簽的含義,如有什么遺漏或是錯(cuò)誤還望多多發(fā)言補(bǔ)充,我會(huì)繼續(xù)完善。
注: 關(guān)于參數(shù)指定jdbcType,是因?yàn)楫?dāng)傳參為null時(shí)候,mybatis無(wú)法自動(dòng)判斷類(lèi)型,就必須要顯示指定它的類(lèi)型,多用于insert中
到此這篇關(guān)于Mybatis中Mapper標(biāo)簽總結(jié)大全的文章就介紹到這了,更多相關(guān)Mybatis Mapper標(biāo)簽內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
淺談Java并發(fā)中ReentrantLock鎖應(yīng)該怎么用
本文主要介紹了ava并發(fā)中ReentrantLock鎖的具體使用,文中通過(guò)示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-11-11
Java算法練習(xí)題,每天進(jìn)步一點(diǎn)點(diǎn)(2)
方法下面小編就為大家?guī)?lái)一篇Java算法的一道練習(xí)題(分享)。小編覺(jué)得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧,希望可以幫到你2021-07-07
一文搞懂JMeter engine中HashTree的配置問(wèn)題
本文主要介紹了JMeter engine中HashTree的配置,文中通過(guò)示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-09-09
Eolink上傳文件到Java后臺(tái)進(jìn)行處理的示例代碼
這篇文章主要介紹了Eolink上傳文件到Java后臺(tái)進(jìn)行處理,這里是上傳的excel表格數(shù)據(jù)并轉(zhuǎn)換為java集合對(duì)象、然后進(jìn)行業(yè)務(wù)邏輯處理判斷最后保存到數(shù)據(jù)庫(kù)?,需要的朋友可以參考下2022-12-12
SpringBoot中配置雙數(shù)據(jù)源的實(shí)現(xiàn)示例
在許多應(yīng)用程序中,可能會(huì)遇到需要連接多個(gè)數(shù)據(jù)庫(kù)的情況,本文主要介紹了SpringBoot中配置雙數(shù)據(jù)源的實(shí)現(xiàn)示例,對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2023-08-08
java中循環(huán)遍歷刪除List和Set集合中元素的方法(推薦)
下面小編就為大家?guī)?lái)一篇java中循環(huán)遍歷刪除List和Set集合中元素的方法(推薦)。小編覺(jué)得挺不錯(cuò)的,在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2016-12-12
Spring?Boot?中的?@HystrixCommand?注解原理及使用方法
通過(guò)使用 @HystrixCommand 注解,我們可以輕松地實(shí)現(xiàn)對(duì)方法的隔離和監(jiān)控,從而提高系統(tǒng)的可靠性和穩(wěn)定性,本文介紹了Spring Boot 中的@HystrixCommand注解是什么,其原理以及如何使用,感興趣的朋友跟隨小編一起看看吧2023-07-07

