Mybatis中Mapper標(biāo)簽總結(jié)大全
一、標(biāo)簽分類
定義SQL語句
- insert
- delete
- update
- select
配置關(guān)聯(lián)關(guān)系
- collection
- association
配置java對象屬性與查詢結(jié)果集中列名的對應(yīng)關(guān)系
- resultMap
控制動態(tài)SQL拼接
- foreach
- if
- choose
格式化輸出
- where
- set
- trim
定義常量
- sql
其他
- include
二、標(biāo)簽總結(jié)
1. 基礎(chǔ)SQL標(biāo)簽
1.1 查詢select
標(biāo)簽屬性
- id 唯一的名稱,對應(yīng)dao中mapper的接口名稱
- paramterType 定義傳入的參數(shù)類型
- resultType 返回數(shù)據(jù)類型對應(yīng)實(shí)體類
- resultMap 外部 resultMap 的命名引用。結(jié)果集的映射是 MyBatis 最強(qiáng)大的特性,對其有一個很好的理解的話,許多復(fù)雜映射的情形都能迎刃而解。使用 resultMap 或 resultType,但不能同時使用
- flushCache 將其設(shè)置為 true,任何時候只要語句被調(diào)用,都會導(dǎo)致本地緩存和二級緩存都會被清空,默認(rèn)值:false
- useCache 將其設(shè)置為 true,將會導(dǎo)致本條語句的結(jié)果被二級緩存,默認(rèn)值:對 select 元素為 true
- timeout 這個設(shè)置是在拋出異常之前,驅(qū)動程序等待數(shù)據(jù)庫返回請求結(jié)果的秒數(shù)。默認(rèn)值為 unset(依賴驅(qū)動)
- fetchSize 這是嘗試影響驅(qū)動程序每次批量返回的結(jié)果行數(shù)和這個設(shè)置值相等。默認(rèn)值為 unset(依賴驅(qū)動)。
- statementType STATEMENT,PREPARED 或 CALLABLE 的一個。這會讓 MyBatis 分別使用 Statement,PreparedStatement 或 CallableStatement,默認(rèn)值:PREPARED。
- resultSetType FORWARD_ONLY,SCROLL_SENSITIVE 或 SCROLL_INSENSITIVE 中的一個,默認(rèn)值為 unset (依賴驅(qū)動)。
- databaseId 如果配置了 databaseIdProvider,MyBatis 會加載所有的不帶 databaseId 或匹配當(dāng)前 databaseId 的語句;如果帶或者不帶的語句都有,則不帶的會被忽略。
- resultOrdered 這個設(shè)置僅針對嵌套結(jié)果 select 語句適用:如果為true,就是假設(shè)包含了嵌套結(jié)果集或是分組了,這樣的話當(dāng)返回一個主結(jié)果行的時候,就不會發(fā)生有對前面結(jié)果集的引用的情況。這就使得在獲取嵌套的結(jié)果集的時候不至導(dǎo)致內(nèi)存不夠用。默認(rèn)值:false。
- resultSets 這個設(shè)置僅對多結(jié)果集的情況適用,它將列出語句執(zhí)行后返回的結(jié)果集并每個結(jié)果集給一個名稱,名稱是逗號分隔的。
/**
* 根據(jù)條件查詢用戶集合
*/
List<User> selectUsers(@Param("cond")Map<String, Object> map);
<!-- 返回的是List,resultType給定的值是List里面的實(shí)體類而不是list,mybatis會自動把結(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 唯一的名稱,對應(yīng)dao中mapper的接口名稱
- parameterType 將要傳入語句的參數(shù)的完全限定類名或別名。這個屬性是可選的,因?yàn)?MyBatis 可以通過 TypeHandler 推斷出具體傳入語句的參數(shù),默認(rèn)值為 unset。
- flushCache 將其設(shè)置為 true,任何時候只要語句被調(diào)用,都會導(dǎo)致本地緩存和二級緩存都會被清空,默認(rèn)值:true(對應(yīng)插入、更新和刪除語句)。
- timeout 這個設(shè)置是在拋出異常之前,驅(qū)動程序等待數(shù)據(jù)庫返回請求結(jié)果的秒數(shù)。默認(rèn)值為 unset(依賴驅(qū)動)。
- statementType STATEMENT,PREPARED 或 CALLABLE 的一個。這會讓 MyBatis 分別使用 Statement,PreparedStatement 或 CallableStatement,默認(rèn)值:PREPARED。
- useGeneratedKeys(僅對 insert 和 update 有用)這會令 MyBatis 使用 JDBC 的 getGeneratedKeys 方法來取出由數(shù)據(jù)庫內(nèi)部生成的主鍵(比如:像 MySQL 和 SQL Server這樣的關(guān)系數(shù)據(jù)庫管理系統(tǒng)的自動遞增字段, oracle使用序列是不支持的,通過selectKey可以返回主鍵),默認(rèn)值:false。
- keyProperty (僅對 insert 和 update 有用)唯一標(biāo)記一個屬性,MyBatis 會通過 getGeneratedKeys 的返回值或者通過 insert 語句的 selectKey子元素設(shè)置它的鍵值,默認(rèn):unset。如果希望得到多個生成的列,也可以是逗號分隔的屬性名稱列表。
- keyColumn(僅對 insert 和 update 有用)通過生成的鍵值設(shè)置表中的列名,這個設(shè)置僅在某些數(shù)據(jù)庫(像PostgreSQL)是必須的,當(dāng)主鍵列不是表中的第一列的時候需要設(shè)置。如果希望得到多個生成的列,也可以是逗號分隔的屬性名稱列表。
- databaseId 如果配置了 databaseIdProvider,MyBatis 會加載所有的不帶 databaseId 或匹配當(dāng)前 databaseId 的語句;如果帶或者不帶的語句都有,則不帶的會被忽略。
<insert id="insert" parameterType="com.it.bean.User">
<!-- 使用序列插入oracle數(shù)據(jù)庫返回主鍵,MYSQL數(shù)據(jù)庫無需添加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語句片段
<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)簽
基本都是用來判斷值是否為空,注意Integer的判斷,mybatis會默認(rèn)把0變成 ‘'
<if test="item != null and item != ''"></if> <!-- 如果是Integer類型的需要把a(bǔ)nd后面去掉或是加上or--> <if test="item != null"></if> <if test="item != null and item != '' or item == 0"></if>
1.3.4 別名
經(jīng)常使用的類型可以定義別名,方便使用,mybatis也注冊了很多別名方便我們使用,詳情見底部附錄
<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)單個對象
標(biāo)簽屬性
- property resultMap返回實(shí)體類中字段和result標(biāo)簽中的property一樣
- column 數(shù)據(jù)庫的列名或者列標(biāo)簽別名,是關(guān)聯(lián)查詢往下一個語句傳送值。注意: 在處理組合鍵時,您可以使用column=“{prop1=col1,prop2=col2}”這樣的語法,設(shè)置多個列名傳入到嵌套查詢語句。這就會把prop1和prop2設(shè)置到目標(biāo)嵌套選擇語句的參數(shù)對象中。
- javaType 一般為ArrayList或是java.util.List
- ofType java的實(shí)體類,對應(yīng)數(shù)據(jù)庫表的列名稱,即關(guān)聯(lián)查詢select對應(yīng)返回的類
- select 執(zhí)行一個其他映射的sql語句返回一個java實(shí)體類型
/**
*問題表
*/
public class Question {
private Long id; //問題id
private String question; //問題
private Integer questionType; //問題類型
private List<QuestionAnswer> answerList; //問題選項集合
//Getter和Setter省略
}
/**
*問題選項表
*/
public class QuestionAnswer {
private Long id; //選項id
private Long questionId; //問題id
private String answer; //選項
//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)識
- type 返回類型
- extends 繼承別的resultMap,可選
關(guān)聯(lián)其他標(biāo)簽
- id 設(shè)置主鍵使用,使用此標(biāo)簽配置映射關(guān)系(可能不止一個)
- result 一般屬性的配置映射關(guān)系,一般不止一個
- association 關(guān)聯(lián)一個對象使用
- collection 關(guān)聯(lián)一個集合使用
<!-- 返回關(guān)聯(liá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>
<!-- 查詢問題集 -->
<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>
<!-- 查詢對應(yīng)問題的答案集 -->
<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)的開頭
- 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用來去掉多條件查詢時,開頭多余的and
<select id="selectUserList" parameterType="com.it.bean.User" resultType="com.it.bean.User">
<!-- 引用Sql片段 -->
select <include refid="selectParam"> from user u
<where>
<!--where 可以自動去掉條件中的第一個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提供的一個智能標(biāo)記,當(dāng)在update語句中使用if標(biāo)簽時,如果前面的if沒有執(zhí)行,則或?qū)е露禾柖嘤噱e誤。使用set標(biāo)簽可以將動態(tài)的配置SET 關(guān)鍵字,和剔除追加到條件末尾的任何不相關(guān)的逗號。
沒有使用if標(biāo)簽時,如果有一個參數(shù)為null,都會導(dǎo)致錯誤,如下示例:
<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)記是一個格式化的標(biāo)記,可以完成set或者是where標(biāo)記的功能
標(biāo)簽屬性
- prefix、suffix 表示再trim標(biāo)簽包裹部分的前面或后面添加內(nèi)容(注意:是沒有prefixOverrides,suffixOverrides的情況下)
- prefixOverrides,suffixOverrides 表示覆蓋內(nèi)容,如果只有這兩個屬性表示刪除內(nèi)容
<update id="test" parameterType="com.it.bean.User">
update user
<!-- 開頭加上set,結(jié)尾去除最后一個逗號 -->
<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)簽
有時候我們并不想應(yīng)用所有的條件,而只是想從多個選項中選擇一個。MyBatis提供了choose 元素,按順序判斷when中的條件出否成立,如果有一個成立,則choose結(jié)束。當(dāng)choose中所有when的條件都不滿則時,則執(zhí)行 otherwise中的sql。類似于Java 的switch 語句,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)注冊好的別名表
| 別名 | 映射類型 |
|---|---|
| _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 |
二、寫在后面
在網(wǎng)上看了很多標(biāo)簽的解釋,但不是很全,我就自己總結(jié)了一份,搭配示例更好理解標(biāo)簽的含義,如有什么遺漏或是錯誤還望多多發(fā)言補(bǔ)充,我會繼續(xù)完善。
注: 關(guān)于參數(shù)指定jdbcType,是因?yàn)楫?dāng)傳參為null時候,mybatis無法自動判斷類型,就必須要顯示指定它的類型,多用于insert中
到此這篇關(guān)于Mybatis中Mapper標(biāo)簽總結(jié)大全的文章就介紹到這了,更多相關(guān)Mybatis Mapper標(biāo)簽內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
SpringBoot中實(shí)現(xiàn)Redis緩存預(yù)熱
緩存預(yù)熱是一種在系統(tǒng)啟動后,但在實(shí)際使用前將數(shù)據(jù)加載到緩存中的技術(shù),本文主要來和大家一起探討如何在Spring Boot應(yīng)用程序中實(shí)現(xiàn)Redis緩存預(yù)熱,以確保系統(tǒng)在處理請求前就已經(jīng)處于最佳狀態(tài),感興趣的可以了解下2023-11-11
Java 關(guān)鍵字static詳解及實(shí)例代碼
這篇文章主要介紹了Java 關(guān)鍵字static詳解及實(shí)例代碼的相關(guān)資料,需要的朋友可以參考下2017-04-04
SpringBoot利用@Retryable注解實(shí)現(xiàn)接口重試
本文主要介紹了springboot如何利用@Retryable注解實(shí)現(xiàn)接口重試功能,文中示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2022-06-06
Java?ObjectMapper的使用和使用過程中遇到的問題
在Java開發(fā)中,ObjectMapper是Jackson庫的核心類,用于將Java對象序列化為JSON字符串,或者將JSON字符串反序列化為Java對象,這篇文章主要介紹了Java?ObjectMapper的使用和使用過程中遇到的問題,需要的朋友可以參考下2024-07-07
SpringBoot解決同名類導(dǎo)致的bean名沖突bean name conflicts問題
這篇文章主要介紹了SpringBoot解決同名類導(dǎo)致的bean名沖突bean name conflicts問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-06-06

