學習MyBatis 動態 SQL
sql教學介紹SQL MyBatis的強大特性SQL
#推薦(免費):sql教學
#動態SQL
MyBatis 的強大功能之一就是它的動態SQL。如果你有使用 JDBC 或其它類似框架的經驗,你就能體會到根據不同條件拼接 SQL 語句的痛苦。例如拼接時要確保不能忘記加入必要的空格,也要注意去掉列表最後一個列名的逗號。利用動態 SQL 這項特性可以徹底擺脫這種痛苦。
雖然在先前使用動態 SQL 並非一件易事,但正是 MyBatis 提供了可以被用在任意 SQL 映射語句中的強大的動態 SQL 語言得以改進這種情況。
動態 SQL 元素和 JSTL 或基於類似 XML 的文字處理器相似。在 MyBatis 之前的版本中,有許多元素需要花時間了解。 MyBatis 3 大大精簡了元素種類,現在只需學習原來一半的元素便可。 MyBatis 採用功能強大的基於 OGNL 的表達式來淘汰其它大部分元素。
準備
先建立User實體類別
public class User { private Integer id; private String username; private String userEmail; private String userCity; private Integer age;}
建立user表CREATE TABLE user (
id int(11) NOT NULL AUTO_INCREMENT,
username varchar(255) DEFAULT NULL,
user_email varchar(255) DEFAULT NULL,
user_city varchar(255) DEFAULT NULL,
age int(11) DEFAULT NULL,
PRIMARY KEY (id))
登入後複製
CREATE TABLE user ( id int(11) NOT NULL AUTO_INCREMENT, username varchar(255) DEFAULT NULL, user_email varchar(255) DEFAULT NULL, user_city varchar(255) DEFAULT NULL, age int(11) DEFAULT NULL, PRIMARY KEY (id))
if
定義介面方法
public List<User> findByUser(User user);
介面對應的Mapper.xml 定義如下所示
<select id="findByUser" resultType="com.example.mybatis.entity.User"> select id, username, user_email userEmail, user_city userCity, age from user where <if test="username != null and username != ''"> username = #{username} </if> <if test="userEmail != null and userEmail != ''"> and user_email = #{userEmail} </if> <if test="userCity != null and userCity != ''"> and user_city = #{userCity} </if></select>
如果if標籤上的test為true,那麼if標籤裡面的SQL語句將會被拼接。
如果username、userEmail、userCity都不為空,那麼SQL將會拼接成如下所示
select id, username, user_email userEmail, user_city userCity, age from user where username = ? and user_email = ? and user_city = ?
如果只有username不為空,那麼SQL將會拼接成如下所示
select id, username, user_email userEmail, user_city userCity, age from user where username = ?
但這種方式有一個缺點,假設此時username為空,userEmail、userCity都不為空。
我們來分析動態SQL 程式碼,現在沒有給username 賦值,也就是username==null,所以「username=#{username}」 這段程式碼不會加入到SQL 語句中,那麼最終拼接好的動態SQL 是這樣的:<div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">select id, username, user_email userEmail, user_city userCity, age
from user where and user_email = ? and user_city = ?</pre><div class="contentsignin">登入後複製</div></div>
where 後面直接跟and,很明顯的語法錯誤,此時應該把緊跟在where
後面的and
刪掉。為了解決這個問題,可以使用
標籤。
where
將上面的SQL改成如下圖<div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false"> <select id="findByUser" resultType="com.example.mybatis.entity.User">
select
id, username, user_email userEmail, user_city userCity, age from user
<where>
<if test="username != null and username != &#39;&#39;">
username = #{username}
</if>
<if test="userEmail != null and userEmail != &#39;&#39;">
and user_email = #{userEmail}
</if>
<if test="userCity != null and userCity != &#39;&#39;">
and user_city = #{userCity}
</if>
</where>
</select></pre><div class="contentsignin">登入後複製</div></div>
如果where
標籤裡面的if
標籤有滿足條件的,那麼where
標籤就會被拼接成where語句,若
標籤拼接的SQL最前面有and語句,那麼這個and將會被刪除。使用這種方法, 會自動刪除SQL中不需要的關鍵字,所以一般 if 標籤和 where 標籤會組合起來使用。
trimtrim
標籤中的prefix
和
屬性會被用來生成實際的SQL 語句,會跟標籤內部的語句拼接。 如果語句的前面或後面遇到
prefixOverrides
或
屬性中指定的值,MyBatis 會自動刪除它們。在指定多個值的時候,別忘了每個值後面都要有一個空格,保證不會和後面的 SQL 連接在一起。
prefix:在拼接的SQL語句中加上一個前綴
suffix:在拼接的SQL語句中加上一個字尾
##prefixOverrides
:拼接的SQL語句前面遇到
,MyBatis 會自動將它們刪除suffixOverrides
:拼接的SQL語句後面遇到
,MyBatis 會自動刪除它們下面使用
標籤來實作where標籤的功能
<select id="findByUser" resultType="com.example.mybatis.entity.User"> select id, username, user_email userEmail, user_city userCity, age from user <trim prefix="where" prefixOverrides="and"> <if test="username != null and username != ''"> username = #{username} </if> <if test="userEmail != null and userEmail != ''"> and user_email = #{userEmail} </if> <if test="userCity != null and userCity != ''"> and user_city = #{userCity} </if> </trim> </select>
如果username為空,userEmail和userCity不為空,那麼
if 標籤拼接的SQL語句如下所示and user_email = #{userEmail} and user_city = #{userCity}
登入後複製因為
trimand user_email = #{userEmail} and user_city = #{userCity}
標籤設定了prefixOverrides=”and” ,而上面的SQL前面有and語句,所以需要將上面的and語句刪掉,又因為
trim標籤設定了prefix=”where”,所以需要在拼接的SQL語句前面加一個where語句
最後
trim標籤的SQL語句被拼接成如下所示where user_email = #{userEmail} and user_city = #{userCity}
登入後複製
where user_email = #{userEmail} and user_city = #{userCity}
choose
有時我們不想應用到所有的條件語句,而只想從中擇其一項。針對這種情況,MyBatis 提供了 choose 元素,它有點像 Java 中的 switch 語句。 <select id="findByUser" resultType="com.example.mybatis.entity.User">
select
id, username, user_email userEmail, user_city userCity, age
from user <where>
<choose>
<when test="username != null and username != ''">
username = #{username} </when>
<when test="userEmail != null and userEmail != ''">
and user_email = #{userEmail} </when>
<when test="userCity != null and userCity != ''">
and user_city = #{userCity} </when>
</choose>
</where>
</select>
public int updateUser(User user);
<update id="updateUser" parameterType="com.example.mybatis.entity.User"> update user <set> <if test="username != null and username != ''"> username=#{username}, </if> <if test="userEmail != null and userEmail != ''"> user_email=#{userEmail}, </if> <if test="userCity != null and userCity != ''"> user_city=#{userCity}, </if> <if test="age != null"> age=#{age} </if> </set> where id=#{id} </update>
接口定义如下所示
public List<User> getUsersByIds(List<Integer> ids);
接口对应的 Mapper.xml 定义如下所示
<!-- collection: 指定要遍历的集合 默认情况下 如果为Collection类型的,key为collection; 如果为List类型的,key为list 如果是数组类型,key为array 可以通过@Param("ids")来指定key item: 将当前遍历的元素赋值给指定的变量 open: 给遍历的结果添加一个开始字符 close: 给遍历的结果添加一个结束字符 separator: 每个元素之间的分隔符 --><select id="getUsersByIds" resultType="com.example.mybatis.entity.User"> select * from user where id in <foreach collection="list" item="id" open="(" close=")" separator=","> #{id} </foreach></select>
用于批量插入
接口定义如下所示
public int addUserList(List<User> users);
接口对应的 Mapper.xml 定义如下所示
<insert id="addUserList" parameterType="com.example.mybatis.entity.User"> insert into user (username, user_email, user_city, age) values <foreach item="user" collection="list" separator=","> (#{user.username}, #{user.userEmail}, #{user.userCity}, #{user.age}) </foreach></insert><!--返回自增主键--><insert id="addUserList" parameterType="com.example.mybatis.entity.User" useGeneratedKeys="true" keyProperty="id"> insert into user (username, user_email, user_city, age) values <foreach item="user" collection="list" separator=","> (#{user.username}, #{user.userEmail}, #{user.userCity}, #{user.age}) </foreach></insert><!--还可以这样写--><!-- 这种方式需要数据库连接属性设置allowMultiQueries=true 这种分号分隔多个SQL还可以用于其他的批量操作,如修改、删除 --><insert id="addUserList" parameterType="com.example.mybatis.entity.User"> <foreach item="user" collection="list" separator=";"> insert into user (username, user_email, user_city, age) values (#{user.username}, #{user.userEmail}, #{user.userCity}, #{user.age}) </foreach></insert><!--如果是Oracle数据库,则需要这样写--><insert id="addUserList" parameterType="com.example.mybatis.entity.User"> <foreach item="user" open="begin" close="end;" collection="list"> insert into user (username, user_email, user_city, age) values (#{user.username}, #{user.userEmail}, #{user.userCity}, #{user.age}); </foreach></insert>
以上是學習MyBatis 動態 SQL的詳細內容。更多資訊請關注PHP中文網其他相關文章!

熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

AI Hentai Generator
免費產生 AI 無盡。

熱門文章

熱工具

記事本++7.3.1
好用且免費的程式碼編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
強大的PHP整合開發環境

Dreamweaver CS6
視覺化網頁開發工具

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

熱門話題

HQL和SQL在Hibernate框架中進行比較:HQL(1.物件導向語法,2.資料庫無關的查詢,3.類型安全),而SQL直接操作資料庫(1.與資料庫無關的標準,2.可執行複雜查詢和資料操作)。

《OracleSQL中除法運算的用法》在OracleSQL中,除法運算是常見的數學運算之一。在資料查詢和處理過程中,除法運算可以幫助我們計算欄位之間的比例或得出特定數值的邏輯關係。本文將介紹OracleSQL中除法運算的用法,並提供具體的程式碼範例。一、OracleSQL中除法運算的兩種方式在OracleSQL中,除法運算可以用兩種不同的方式來進行

Oracle和DB2是兩個常用的關聯式資料庫管理系統,它們都有自己獨特的SQL語法和特性。本文將針對Oracle和DB2的SQL語法進行比較與區別,並提供具體的程式碼範例。資料庫連接在Oracle中,使用以下語句連接資料庫:CONNECTusername/password@database而在DB2中,連接資料庫的語句如下:CONNECTTOdataba

MyBatis動態SQL標籤解讀:Set標籤用法詳解MyBatis是一個優秀的持久層框架,它提供了豐富的動態SQL標籤,可以靈活地建構資料庫操作語句。其中,Set標籤是用來產生UPDATE語句中SET子句的標籤,在更新作業中非常常用。本文將詳細解讀MyBatis中Set標籤的用法,以及透過具體的程式碼範例來示範其功能。什麼是Set標籤Set標籤用於MyBati

解決方法:1、檢查登入使用者是否具有足夠的權限來存取或操作該資料庫,確保該使用者俱有正確的權限;2、檢查SQL Server服務的帳戶是否具有存取指定檔案或資料夾的權限,確保該帳戶具有足夠的權限來讀取和寫入該文件或資料夾;3、檢查指定的資料庫文件是否已被其他進程打開或鎖定,嘗試關閉或釋放該文件,並重新運行查詢;4、嘗試以管理員身份運行Management Studio等等。

資料庫技術大比拼:Oracle和SQL的差別有哪些?在資料庫領域中,Oracle和SQLServer是兩種備受推崇的關聯式資料庫管理系統。儘管它們都屬於關係型資料庫的範疇,但兩者之間存在著許多不同之處。在本文中,我們將深入探討Oracle和SQLServer之間的區別,以及它們在實際應用中的特徵和優勢。首先,Oracle和SQLServer在語法方面存

MyBatis的快取機制解析:一級快取與二級快取的差異與應用在MyBatis框架中,快取是一個非常重要的特性,可以有效提升資料庫操作的效能。其中,一級快取和二級快取是MyBatis常用的兩種快取機制。本文將詳細解析一級快取與二級快取的差異與應用,並提供具體的程式碼範例進行說明。一、一級緩存一級緩存也被稱為本地緩存,它預設開啟且不可關閉。一級快取是SqlSes

MyBatisGenerator是MyBatis官方提供的程式碼產生工具,可以幫助開發人員快速產生符合資料庫表結構的JavaBean、Mapper介面以及XML映射檔。在使用MyBatisGenerator進行程式碼產生的過程中,配置參數的設定是至關重要的。本文將從配置參數的角度出發,深入探討MyBatisGenerator的
