MyBatis
筆記目錄:(https://www.cnblogs.com/wenjie2000/p/16378441.html)
視頻教程(P47~P60)
看前提醒:如果之前學過一些框架,只想知道mybatis怎么用,那么就不太建議看任何第三方教程,更建議直接去看官方檔案,從入門到具體配置都有,如果之前沒學過框架,也建議先試著去看,實在不行再繼續看博客或教學視頻內容,(官方檔案不跟你廢話,內容更加精煉)
什么是MyBatis?
- MyBatis是一款優秀的持久層框架,用于簡化JDBC開發
- MyBatis本是Apache 的一個開源專案iBatis, 2010年這個專案由apache softwarefoundation遷移到了google code,并且改名為MyBatis,2013年11月遷移到Github
- MyBatis官方參考檔案(有中文,必看): https://mybatis.org/mybatis-3/zh/index.html
持久層
- 負責將資料到保存到資料庫的那一層代碼
- JavaEE三層架構:表現層、業務層、持久層
框架
- 框架就是一個半成品軟體,是一套可重用的、通用的、軟體基礎代碼模型
- 在框架的基礎之上構建軟體撰寫更加高效、規范、通用、可擴展
JDBC缺點
- 硬編碼(不方便設定修改 資料庫連接和sql陳述句,不便于后期維護)
- 操作繁瑣(很多引數需要手動設定,需要手動封裝結果集)
MyBatis簡化
- 硬編碼 → 組態檔
- 操作繁瑣 →MyBatis輔助,簡化代碼
MyBatis快速入門
參考網站:https://mybatis.org/mybatis-3/zh/getting-started.html
查詢user表中所有資料
-
創建user表,添加資料
-
創建模塊,匯入坐標(建議先去學習maven基礎)
-
撰寫MyBatis核心組態檔-->替換連接資訊解決硬編碼問題
-
撰寫SQL映射檔案-->統一管理sql陳述句,解決硬編碼問題
-
編碼
-
定義POJO類
-
加載核心組態檔,獲取 SqlSessionFactory 物件
-
獲取SqISession物件,執行SQL陳述句
-
釋放資源
-
具體操作
-
在mysql中創建資料表(直接用,沒必要手敲)(我用的mysql-5.7.38)
DROP TABLE IF EXISTS `t_user`; CREATE TABLE `t_user` ( `id` int(11) NOT NULL AUTO_INCREMENT, `username` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL, `password` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL, `age` int(11) NULL DEFAULT NULL, `gender` char(1) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL, `email` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL, PRIMARY KEY (`id`) USING BTREE ) ENGINE = InnoDB AUTO_INCREMENT = 5 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic; INSERT INTO `t_user` VALUES (1, 'admin', '123456', 23, '男', '[email protected]'); INSERT INTO `t_user` VALUES (2, 'root', '123', 23, '男', '[email protected]'); INSERT INTO `t_user` VALUES (4, 'admin2', '123456', 23, '男', '[email protected]'); -
創建模塊,匯入坐標(考慮到某些人沒學過maven,這里步驟比較詳細,但還是建議先去看maven入門,要不了多少時間,)
IDEA界面中:左上角 File(檔案)-->New(新建)-->Project...(專案)
選擇maven


可以看到生成的結構

將以下內容放到pom.xml中(需要注意依賴、mysql驅動版本)
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>org.example</groupId> <artifactId>mybatis-demo</artifactId> <version>1.0-SNAPSHOT</version> <dependencies> <!--mybatis依賴--> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.7</version> </dependency> <!--mysql驅動 版本僅供參考,根據自己電腦中安裝的mysql版本來--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.9</version> </dependency> <!--junit 單元測驗--> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency> <!--列印日志 需要相應的組態檔--> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency> </dependencies> </project>在resources檔案夾中創建檔案log4j.xml,并且寫入以下內容(內容固定,拿來用就行,不需要背)
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE log4j:configuration SYSTEM "log4j.dtd"> <log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/"> <appender name="STDOUT" > <param name="Encoding" value="https://www.cnblogs.com/wenjie2000/p/UTF-8"/> <layout > <param name="ConversionPattern" value="https://www.cnblogs.com/wenjie2000/p/%-5p %d{MM-dd HH:mm:ss,SSS}%m (%F:%L) /n"/> </layout> </appender> <logger name="java.sql"> <level value="https://www.cnblogs.com/wenjie2000/p/debug"/> </logger> <logger name="org.apache.ibatis"> <level value="https://www.cnblogs.com/wenjie2000/p/info"/> </logger> <root> <level value="https://www.cnblogs.com/wenjie2000/p/debug"/> <appender-ref ref="STDOUT"/> </root> </log4j:configuration> -
撰寫MyBatis核心組態檔
在resources中創建檔案mybatis-config.xml,并寫入以下內容(需要根據自己資料庫修改部分內容):
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <environments default="development"> <environment id="development"> <transactionManager type="JDBC"/> <dataSource type="POOLED"> <!--資料庫鏈接資訊 根據自己情況修改--> <property name="driver" value="https://www.cnblogs.com/wenjie2000/p/com.mysql.jdbc.Driver"/> <property name="url" value="https://www.cnblogs.com/wenjie2000/p/jdbc:mysql://localhost:3306/ssm"/> <property name="username" value="https://www.cnblogs.com/wenjie2000/p/root"/> <property name="password" value="https://www.cnblogs.com/wenjie2000/p/123456"/> </dataSource> </environment> </environments> <mappers> <!--選擇需要加載的sql映射檔案(存放需要執行的sql陳述句的組態檔),下一步會創建--> <mapper resource="UserMapper.xml"/> </mappers> </configuration> -
撰寫SQL映射檔案
在resources檔案夾中創建sql映射檔案mybatis-config.xml(可以根據自己需求命名):
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="test"> <!--resultType為回傳的資料所對應的類--> <select id="selectAll" resultType="com.atguigu.pojo.User"> select * from t_user </select> </mapper>在java檔案夾中創建類com.atguigu.pojo.User (存放查詢資料庫時所回傳的資料)
package com.atguigu.pojo; public class User { private Integer id; private String username; private String password; private Integer age; private String gender; private String email; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } @Override public String toString() { return "User{" + "id=" + id + ", username='" + username + '\'' + ", password='" + password + '\'' + ", age=" + age + ", gender='" + gender + '\'' + ", email='" + email + '\'' + '}'; } } -
編碼
在java檔案夾中創建類com.atguigu.MyBatisDemo ,內容如下(不要背,只需要理解每一步的作用):
package com.atguigu; import com.atguigu.pojo.User; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import java.io.IOException; import java.io.InputStream; import java.util.List; public class MyBatisDemo { public static void main(String[] args) throws IOException { //1.加載mybatis核心組態檔 String resource = "mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); //2.根據組態檔創建SqlSession工廠 SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); //3.通過工廠獲取SqlSession SqlSession sqlSession = sqlSessionFactory.openSession(); //4.用SqlSession執行sql陳述句 此處的“test.selectAll”就是sql映射檔案中的sql陳述句位置 List<User> users = sqlSession.selectList("test.selectAll"); System.out.println(users); //5.釋放資源 sqlSession.close(); } }運行MyBatisDemo,出現以下內容則成功

雖然相對于學習JDBC時只是在一個檔案中操作而言,看起來似乎更加麻煩,但是也需要考慮實際開發中代碼量大和后續維護困難程度的問題,
Mappr代理開發
List<User> users = sqlSession.selectList("test.selectAll");
你可能會注意到,這種方式和用全限定名呼叫 Java 物件的方法類似,這樣,該命名就可以直接映射到在命名空間中同名的映射器類,并將已映射的 select 陳述句匹配到對應名稱、引數和回傳型別的方法,因此你就可以像上面那樣,不費吹灰之力地在對應的映射器介面呼叫方法,就像下面這樣:
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
List<User> users = userMapper.selectAll();
第二種方法有很多優勢,首先它不依賴于字串字面值,會更安全一點;其次,如果你的 IDE 有代碼補全功能,那么代碼補全可以幫你快速選擇到映射好的 SQL 陳述句,
使用Mapper代理方式完成入門案例
-
定義與SQL映射檔案同名的Mapper介面,并且將Mapper介面和SQL映射檔案放置在同一目錄下
由于maven進行編譯會將java檔案夾和resource檔案夾下的內容都放到target/classes檔案夾中,所以只需要兩者對于java和resources檔案夾的相對路徑一致(因此此處沒必要在寫代碼時把組態檔也放到介面同目錄)(注意在resources中創建結構使用“com/atguigu/mapper”的方式,如果使用“com.atguigu.mapper”不會創建多級目錄)

以下為編譯后的檔案結構,兩者在同一目錄中

-
設定SQL映射檔案的namespace屬性為Mapper介面全限定名
namespace="com.atguigu.mapper.UserMapper"
-
在Mapper介面中定義方法,方法名就是SQL映射檔案中sql陳述句的id,并保持引數型別和回傳值型別一致
List<User> selectAll();
修改mybatis組態檔中的sql映射檔案的新的路徑
<mapper resource="com/atguigu/mapper/UserMapper.xml"/>
-
編碼
- 通過SqlSession的 getMapper方法獲取Mapper介面的代理物件
- 呼叫對應方法完成sql的執行
//獲取UserMapper介面的代理物件 UserMapper userMapper = sqlSession.getMapper(UserMapper.class); List<User> users = userMapper.selectAll();
細節:如果Mapper介面名稱和SQL映射檔案名稱相同,并在同一目錄下,則可以使用包掃描的方式簡化SQL映射檔案的加載
方法如下:
修改mybatis組態檔mybatis-config.xml中<mappers>下的內容
<!--sql映射檔案--> <mappers> <!--<mapper resource="com/atguigu/mapper/UserMapper.xml"/>--> <package name="com.atguigu.mapper"/> </mappers>
MyBatis核心組態檔
我只會介紹一些重要的部分,不可能都講完,詳細的可以去官網,
官方檔案(如果需要詳細了解就必須去看):https://mybatis.org/mybatis-3/zh/configuration.html
mybatis-config.xml
environments:配置資料庫連接環境資訊,可以配置多個environment,通過default屬性切換不同的environment
mappers:配置sql映射檔案(上面已經講過了)
typeAliases:型別別名,可以減少需要書寫的類的長度
例如:
在mybatis-config.xml的
中加入下面的內容: <!--掃描"com.atguigu.pojo"下的所有類,并取一個別名,默認為類名(不區分大小寫)--> <typeAliases> <package name="com.atguigu.pojo"/> </typeAliases>
后面需要使用com.atguigu.pojo中的類時就只需要寫類名,前面不需要附加包名,例如包中的User類:
當然,也可以對每個類進行單獨的配置,但一般不使用那種方式,如想了解可以自行去官網查找,
細節:配置各個標簽時,需要遵守下列的前后順序(必須遵守,否則會報錯)
- configuration(配置)
- properties(屬性)
- settings(設定)
- typeAliases(型別別名)
- typeHandlers(型別處理器)
- objectFactory(物件工廠)
- plugins(插件)
- environments(環境配置)
- environment(環境變數)
- transactionManager(事務管理器)
- dataSource(資料源)
- environment(環境變數)
- databaseIdProvider(資料庫廠商標識)
- mappers(映射器)
組態檔完成增刪改查
完成品牌資料的增刪改查操作
產品原型地址:
https://www.pmdaniu.com/storages/122645/74ccff58678d80583ea43a55547173eb-1818/電商后臺高保真原型(首頁).html
-
要完成的功能串列清單:
-
查詢
查詢所有資料
查看詳情
條件查詢
-
添加
-
修改
修改全部欄位
修改動態欄位
-
洗掉
洗掉一個
批量洗掉
-
準備環境
①資料庫表tb_brand
-- 洗掉tb_brand表 drop table if exists tb_brand; -- 創建tb_brand表 create table tb_brand( -- id主鍵 id int primary key auto_increment, -- 品牌名稱 brand_name varchar(20), -- 企業名稱 company_name varchar(20), -- 排序欄位 ordered int, -- 描述資訊 description varchar(100), -- 狀態∶0:禁用1∶啟用 status int ); -- 添加資料 insert into tb_brand (brand_name,company_name,ordered,description,status) values ('三只松鼠','三只松鼠股份有限公司',5,'好吃不上火',0), ('華為','華為技術有限公司', 100,'華為致力于把數字世界帶入每個人、每個家庭、每個組織,構建萬物互聯的智能世界',1), ('小米','小米科技有限公司',50,'are you ok', 1); SELECT * FROM tb_brand;②物體類Brand(放在main/java檔案夾下,位置看package)
package com.atguigu.pojo; public class Brand { private Integer id;//主鍵 private String brandName;//品牌名稱 private String companyName;//企業名稱 private Integer ordered;//排序欄位 private String description;//描述資訊 private Integer status;//狀態 public Integer getId() {return id;} public void setId(Integer id) {this.id = id;} public String getBrandName() {return brandName;} public void setBrandName(String brandName) {this.brandName = brandName;} public String getCompanyName() {return companyName;} public void setCompanyName(String companyName) {this.companyName = companyName;} public Integer getOrdered() {return ordered;} public void setOrdered(Integer ordered) {this.ordered = ordered;} public String getDescription() {return description;} public void setDescription(String description) {this.description = description;} public Integer getStatus() {return status;} public void setStatus(Integer status) {this.status = status;} @Override public String toString() { return "Brand{" + "id=" + id + ", brandName='" + brandName + '\'' + ", companyName='" + companyName + '\'' + ", ordered=" + ordered + ", description='" + description + '\'' + ", status=" + status + '}'; } }后續如果不想寫資料庫表對應的物體類,也可以使用自動生成,(再根據實際需求進行修改):
先連接資料庫(右側的 Database(資料庫) →"+"→Data Source(資料源)→MySQL→配置好資料庫資訊→OK)
創建物體類(也可以使用之前配置好 右側的 Database(資料庫)→schemas→找到表名右鍵→Scripted Extensions(腳本擴展)→Generate POHOs.grovy)
這不是MyBatis的主要內容,我就不詳細說了,
如果想看詳細流程截圖→:https://blog.csdn.net/weixin_42575720/article/details/125093184③測驗用例(放在test/java檔案夾下,位置:src/test/java/com/itheima/test/MyBatisTest.java)
④安裝MyBatisX插件(非必要,但開發更加方便)
MybatisX是一款基于IDEA的快速開發插件,為效率而生,
安裝:
主要功能:
XML和介面方法相互跳轉(通過點擊代碼區域左側的鳥)
根據介面方法生成statement(組態檔中寫sql陳述句的位置)
如果在介面中創建方法,但沒寫對應的組態檔會出現如下報錯(如果不安裝這個插件則不會出現):
Alt+Enter 它可以幫你在組態檔中幫你定義好對應的結構(事先必須要創建組態檔,它不能幫你創建)
框出的內容為它生成的(只需要手動加上sql陳述句)
如果寫sql陳述句時沒提示可以在 設定中→搜索SQL Dialects(SQL方言)→Global SQL Dialect(全域SQL方言)設定為MySQL
1. 查詢
1.1查詢所有資料

和入門案例類似,以下為基本要點(一定要自己上手,可以復制之前寫的代碼再修改)

代碼參考:
package com.atguigu.mapper;
import com.atguigu.pojo.Brand;
import java.util.List;
public interface BrandMapper {
List<Brand> selectAll();
}
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.atguigu.mapper.BrandMapper">
<select id="selectAll" resultType="Brand">
SELECT * FROM tb_brand
</select>
</mapper>
package com.itheima.test;
import com.atguigu.mapper.BrandMapper;
import com.atguigu.pojo.Brand;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
public class MyBatisTest {
@Test
public void testSelectAll() throws IOException {
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);
List<Brand> brands = brandMapper.selectAll();
for (Brand brand : brands) {
System.out.println(brand);
}
sqlSession.close();
}
}
運行結果:

這里可以看到 brandName和companyName并沒有獲取到資料,是因為資料庫中(brand_name,company_name)和物體類欄位名稱( brandName,companyName)不一樣,對不上,需要手動設定,
方法一 起別名:修改sql陳述句,對不一樣的列名起別名,讓別名和物體類的屬性名一樣(缺點:每次查詢都要定義一次別名,不推薦)
方法二 resultMap(結果映射):
- 定義<resultMap>標簽
- 在<select>標簽中使用resultMap屬性替換resultType屬性
具體修改如下所示(注意看我的注釋):
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.atguigu.mapper.BrandMapper"> <!-- id:唯一標識 type:映射的型別,支持別名 --> <resultMap id="brandResultMap" type="brand"> <!-- id:完成主鍵欄位的映射 column:表的列名 property:物體類的屬性名 result:完成一般欄位的映射 column:表的列名 property:物體類的屬性名 --> <result property="brandName" column="brand_name"/> <result property="companyName" column="company_name"/> </resultMap> <select id="selectAll" resultMap="brandResultMap"> SELECT * FROM tb_brand </select> </mapper>現在就能正常顯示了
1.2查看詳情

注意其中組態檔中的#{id}與方法中的id對應,為用作傳遞引數的引數占位符,

//測驗方法
@Test
public void testSelectById() throws IOException {
int id=1;//接收引數
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);
Brand brand = brandMapper.selectById(id);
System.out.println(brand);
sqlSession.close();
}

引數占位符:
- #{}:會將其替換為?,為了防止SQL注入,(詳細情況我在JDBC中的Statement部分內容有說明)
- ${}:拼接SQL,會存在SQL注入問題,(盡量不用)
- 使用時機:
- 引數傳遞的時候:#{}
- 表名或者列名不固定的情況下:${}會存在SQL注入問題
注意特殊字符需要特地處理:
例如select * from tb_brand where id<3;由于是在xml檔案中“<”不能被正常識別,
-
轉義字符
< 改為 <
-
CDATA區(輸入CD會出現提示)
<![CDATA[ < ]]>
1.3條件查詢

條件查詢中經常會出現傳入多個引數的情況,此時就不能只用之前的傳參方式了(因為不知道怎么匹配),
處理方法是在介面中對應方法處指出對應關系,
方式如下,主要內容已經給出(不難,我就不粘貼完整代碼了,自己完成)

SQL陳述句設定多個引數的三種方式
-
散裝引數:需要使用@Param("SQL中的引數占位符名稱")
@Param("組態檔中的標識")形參(例如:@Param("status")int status)
如果不加@Param(""),mybatis就會自動命名,(mybatis會默認使用arg0,arg1,arg2....或param1,param2,param3...作為標識)
-
物體類封裝引數
*只需要保證SQL中的引數名和物體類屬性名對應上,即可設定成功
將引數放到物體類物件中,直接傳該物件,其中變數名對應標識,變數名對應值,
(例如:此處可以把status、companyName、brandName存放到Brand物件中) -
map集合
*只需要保證SQL中的引數名和map集合的鍵的名稱對應上,即可設定成功
創建hashMap,將組態檔中的識別符號作為key,對應的值為value存放到其中,
但是上面這樣寫SQL陳述句在實際使用中會出現Bug,因為當存在框中內容為空的情況下,sql陳述句對應位置的引數就為null,因而導致查詢結果錯誤,因此需要用到動態SQL
動態SQL
官方教程:https://mybatis.org/mybatis-3/zh/dynamic-sql.html
SQL陳述句會隨著用戶的輸入或外部條件的變化而變化,我們稱為動態SQL
-
MyBatis 對動態SQL有很強大的支撐,利用下列標簽可以實作動態SQL:
if
choose (when, otherwise)
trim (where, set)
foreach
if
用于判斷引數是否有值,使用test屬性進行條件判斷
使用動態 SQL 最常見情景是根據條件包含 where 子句的一部分,比如:
<select id="selectByCondition" resultMap="brandResultMap">
SELECT * FROM tb_brand
WHERE id = 1
<if test="status != null">
AND status = #{status}
</if>
</select>
對于之前的題目,就能利用if判斷是否有值來執行動態的SQL陳述句,
但是對于存在多個搜索條件的情況下,則會出現一些問題,例如:
# 第一個條件不需要邏輯運算子and,or等連接
select * from tb_brand where
status = #{status}
and company_name like #{companyName}
and brand_name like #{brandName}
對于上面的sql陳述句,轉換為動態SQL,需要進行針對性的處理,對此有兩種方法:
-
使用恒等式(加入1=1)(僅需了解,實際情況盡量不用或少用)
select * from tb_brand where 1=1 <if test="status != null"> and status = #{status} </if> <if test="companyName != null"> and company_name like #{companyName} </if> <if test="brandName != null"> and brand_name like #{brandName} </if> -
使用
替換where關鍵字(where標簽很智能,如果where后面跟的有and,會自動洗掉,如果where后面沒內容,where也會洗掉) select * from tb_brand <where> <if test="status != null"> and status = #{status} </if> <if test="companyName != null"> and company_name like #{companyName} </if> <if test="brandName != null"> and brand_name like #{brandName} </if> <where>
choose (when, otherwise)
choose有點像 Java 中的 switch 陳述句,
select *
from tb_brand where
<choose> <!--類似于switch-->
<when test="status !=null"> <!--類似于case-->
status= #{status}
</when>
<when test="companyName != null and companyName !=''">
company_name like #{companyName}
</when>
<when test="brandName != null and brandName !=''">
brand_name like #{brandName}
</when>
<otherwise> <!--類似于default-->
1=1
</otherwise>
</choose>
2.添加
要點已給出,具體代碼自行完成.(注意這里不用<select>,使用<insert>)

有些人會出現程式運行成功,但資料庫中沒有資料的情況,是因為mybatis默認開啟事務,只需在創建sqlSession時,傳入引數true(設定是否自動提交),或是執行后加上sqlSession.commit();實作手動提交
SqlSession sqlSession = sqlSessionFactory.openSession(true);
添加-主鍵回傳
經常會出現添加資料后需要獲取資料對應的主鍵,
可以使用物體類封裝引數(例如此處的Brand brand),然后將獲取的主鍵存放到物件中(然后再訪問brand中存放的主鍵值),

3.修改
3.1 修改全部欄位

3.2修改動態欄位
注意此處可以用<set>標簽代替set,(<set>可以去掉末尾的逗號,如果<set>中沒有內容,則不會加上set)

4.洗掉
4.1洗掉一個

4.2批量洗掉

注意:mybatis默認會將陣列引數封裝為一個Map集合,
- 默認key為“array”,value為陣列
- 也可以使用@Param注解改變map集合的默認key的名稱(例如:@Param("ids")int[] ids)
MyBatis引數傳遞
MyBatis介面方法中可以接收各種各樣的引數,MyBatis底層對于這些引數進行不同的封裝處理方式(MyBatis提供了ParamNameResolver類來進行引數封裝)
如果想要加深理解可以去看原始碼或視頻(原始碼部分筆記不好寫):https://www.bilibili.com/video/BV1Qf4y1T7Hx/?p=59
單個引數:
POJO型別:直接使用,鍵名和引數占位符名稱一致
Map集合:直接使用,鍵名和引數占位符名稱一致
Collection:封裝為Map集合,,可以使用@Param注解,替換Map集合中默認的arg鍵名
map.put("arg0",collection集合);
map.put("collection",collection集合);
List:封裝為Map集合,,可以使用@Param注解,替換Map集合中默認的arg鍵名
map.put("arg0",list集合);
map.put("collection",list集合);
map.put("list",list集合);
Array:封裝為Map集合,可以使用@Param注解,替換Map集合中默認的arg鍵名
map.put("arg0",array集合);
map.put("array",array集合);
其他型別(例如int):直接用,#{}中寫啥都能接收到
多個引數:封裝為Map集合(但不推薦使用默認的,因為可讀性差,過段時間再看就不知道傳的是什么東西了,建議∶將來都使用@Param注解來修改Map集合中默認的鍵名(arg)、并使用修改后的名稱來獲取值,這樣可讀性更高!
map.put("arg0",引數1)
map.put("arg1",引數2)
map.put("param1",引數1)
map.put("param2",引數2)
---------------------------------(@Param("username")引數1,引數2)
map.put("username",引數1)
map.put("arg1",引數2)
map.put("param1",引數1)
map.put("param2",引數2)
使用注解完成增刪改查
使用注解開發會比組態檔開發更加方便(僅針對完成簡單的功能)
@Select("select * from tb_user where id = #{id}")
public User selectByld(int id);

轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/541463.html
標籤:Java
上一篇:學習筆記——Maven的核心概念之倉庫、坐標;maven的依賴管理;Maven中統一管理版本號;Maven的繼承;Maven的聚合
下一篇:Java方法








