Java Web 開(kāi)發(fā)從入門(mén)到實(shí)踐課件 第13章 - MyBatis框架_第1頁(yè)
Java Web 開(kāi)發(fā)從入門(mén)到實(shí)踐課件 第13章 - MyBatis框架_第2頁(yè)
Java Web 開(kāi)發(fā)從入門(mén)到實(shí)踐課件 第13章 - MyBatis框架_第3頁(yè)
Java Web 開(kāi)發(fā)從入門(mén)到實(shí)踐課件 第13章 - MyBatis框架_第4頁(yè)
Java Web 開(kāi)發(fā)從入門(mén)到實(shí)踐課件 第13章 - MyBatis框架_第5頁(yè)
已閱讀5頁(yè),還剩28頁(yè)未讀 繼續(xù)免費(fèi)閱讀

下載本文檔

版權(quán)說(shuō)明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請(qǐng)進(jìn)行舉報(bào)或認(rèn)領(lǐng)

文檔簡(jiǎn)介

JavaWeb開(kāi)發(fā)從入門(mén)到實(shí)踐JavaWebDevelopmentFromIntroductiontoPracticeMyBatis框架Chap13提綱MyBatis框架本章介紹MyBatis的基本操作與XML映射配置文件的使用,講解了分頁(yè)查詢實(shí)現(xiàn)和跨域訪問(wèn)數(shù)據(jù)的處理方法,幫助開(kāi)發(fā)者高效地進(jìn)行數(shù)據(jù)訪問(wèn)與管理。13.1MyBatis基本操作13.2XML映射配置文件13.3分頁(yè)查詢13.4跨域訪問(wèn)數(shù)據(jù)13.5本章小結(jié)13.1MyBatis基本操作13.1.1MyBatis概念13.1.2MyBatis基礎(chǔ)操作13.1.1MyBatis概念MyBatis是支持定制化SQL、存儲(chǔ)過(guò)程以及高級(jí)映射的優(yōu)秀的持久層框架,它內(nèi)部封裝了JDBC,使開(kāi)發(fā)者只需要關(guān)注SQL本身,而不需要花費(fèi)精力去處理諸如注冊(cè)驅(qū)動(dòng)、創(chuàng)建Connection對(duì)象等JDBC的繁瑣過(guò)程。MyBatis的主要特點(diǎn)如下。(1)SQL映射:MyBatis直接使用SQL,可以將接口與SQL語(yǔ)句綁定,運(yùn)行時(shí)動(dòng)態(tài)地生成SQL語(yǔ)句。(2)簡(jiǎn)化JDBC使用:減少編寫(xiě)重復(fù)的JDBC代碼,使代碼更加簡(jiǎn)潔。(3)無(wú)侵入性:MyBatis完全依賴于接口,不會(huì)影響原始的代碼結(jié)構(gòu)。(4)靈活性:MyBatis的SQL直接寫(xiě)在XML或注解中,可以隨時(shí)修改SQL語(yǔ)句,不影響原始Java代碼。(5)動(dòng)態(tài)SQL:支持動(dòng)態(tài)SQL,可以根據(jù)不同的條件生成不同的SQL語(yǔ)句。(6)與Spring集成:MyBatis可以與Spring框架無(wú)縫集成,簡(jiǎn)化了配置過(guò)程。13.1.2MyBatis基礎(chǔ)操作案例:MyBatis基礎(chǔ)操作1、創(chuàng)建一個(gè)SpringBoot工程,選擇引入對(duì)應(yīng)的起步依賴(mybatis、mysql驅(qū)動(dòng)、lombok和web)。2、perties中引入數(shù)據(jù)庫(kù)連接信息,啟動(dòng)MyBatis的日志功能,并指定輸出到控制臺(tái)。spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driverspring.datasource.url=jdbc:mysql://localhost:3306/mybatisspring.datasource.username=root

spring.datasource.password=123456

mybatis.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl3、創(chuàng)建數(shù)據(jù)庫(kù)表emp和對(duì)應(yīng)的實(shí)體類Emp13.1.2MyBatis基礎(chǔ)操作createtableemp(

idintunsignedprimarykeyauto_incrementcomment'ID',

usernamevarchar(20)notnulluniquecomment'用戶名',

passwordvarchar(32)default'123456'comment'密碼',

namevarchar(10)notnullcomment'姓名',

gendertinyintunsignednotnullcomment'性別,說(shuō)明:1男,0女',

imagevarchar(300)comment'圖像',

jobtinyintunsignedcomment'職位:1專任教師,2輔導(dǎo)員,3其它,

entrydatedatecomment'入職時(shí)間',

dept_idintunsignedcomment'部門(mén)ID',

create_timedatetimenotnullcomment'創(chuàng)建時(shí)間',

update_timedatetimenotnullcomment'修改時(shí)間')comment'員工表';13.1.2MyBatis基礎(chǔ)操作@Data@AllArgsConstructor@NoArgsConstructorpublicclassEmp{ privateIntegerid; privateStringusername; privateStringpassword; privateStringname; privateShortgender; privateStringimage; privateshortjob; privateLocalDateentrydate; privateIntegerdeptId; privateLocalDateTimecreateTime; privateLocalDateTimeupdateTime;}13.1.2MyBatis基礎(chǔ)操作4、準(zhǔn)備Mapper接口EmpMapperMyBatis支持參數(shù)占位符,MyBatis對(duì)于字符參數(shù)和非字符參數(shù)提供了兩種不同的參數(shù)占位符,字符類型的參數(shù)使用${},而非字符類型的參數(shù)使用#{}。(1)#{}

執(zhí)行SQL時(shí),會(huì)將#{}替換為?,生成預(yù)編譯SQL,會(huì)自動(dòng)設(shè)置參數(shù)值,適用于參數(shù)傳遞。(2)${}

拼接SQL。namelikeconcat('%',#{name},'%')13.1.2MyBatis基礎(chǔ)操作增加、刪除操作@Mapper

publicinterfaceEmpMapper{

@Options(keyProperty="id",useGeneratedKeys=true)

@Insert("INSERTINTOemp(username,password,name,gender,image,job,entrydate,dept_id,create_time,update_time)VALUES(#{username},#{password},#{name},#{gender},#{image},#{job},#{entrydate},#{deptId},#{createTime},#{updateTime})")

publicvoidinsert(Empemp);

@Delete("deletefromempwhereid=#{id}")

publicvoiddelete(Integerid);

13.1.2MyBatis基礎(chǔ)操作修改、查詢操作@Update("updateempsetusername=#{username},password=#{password},name=#{name},gender=#{gender},image=#{image},job=#{job},entrydate=#{entrydate},dept_id=#{deptId},create_time=#{createTime},update_time=#{updateTime}"+"whereid=#{id}")

publicvoidupdate(Empemp);

@Select("select*fromempwhereid=#{id}")

publicEmpgetById(Integerid);

@Select("select*fromempwherenamelikeconcat('%',#{name},'%')andgender=#{gender}andentrydatebetween#{begin}and#{end}")

publicList<Emp>list(Stringname,Shortgender,LocalDatebegin,LocalDateend);

}13.1.2MyBatis基礎(chǔ)操作5、數(shù)據(jù)封裝實(shí)體類屬性名和數(shù)據(jù)庫(kù)字段名一致,MyBatis會(huì)自動(dòng)封裝,如果實(shí)體類屬性名和數(shù)據(jù)庫(kù)字段名不一致,不能自動(dòng)封裝,這種情況進(jìn)行封裝有以下三種方式。(1)起別名。在SQL語(yǔ)句中,對(duì)不一樣的列名起別名,保持別名和實(shí)體類屬性名一致。@Select("selectid,username,password,name,gender,image,job,entrydate,dept_iddeptId,create_timecreateTime,update_timeupdateTimefromempwhereid=#{id}")

publicEmpgetById(Integerid);(2)手動(dòng)設(shè)置結(jié)果映射。通過(guò)@Results及@Result手動(dòng)設(shè)置結(jié)果映射。@Select("select*fromempwhereid=#{id}")@Results({@Result(column="dept_id",property="deptId"),@Result(column="create_time",property="createTime"),@Result(column="update_time",property="updateTime")})publicEmpgetById(Integerid);13.1.2MyBatis基礎(chǔ)操作(3)開(kāi)啟駝峰命名。如果字段名與屬性名符合駝峰命名規(guī)則,MyBatis會(huì)自動(dòng)通過(guò)駝峰命名規(guī)則映射,在perties中進(jìn)行設(shè)置mybatis.configuration.map-underscore-to-camel-case=true13.2XML映射配置文件13.2.1XML映射文件13.2.2MyBatis動(dòng)態(tài)SQL13.2.1XML映射文件使用XML映射文件需要遵守以下規(guī)范。(1)XML映射文件的名稱與Mapper接口名稱一致,并且將XML映射文件和Mapper接口放置在相同包下。(2)XML映射文件的namespace屬性與Mapper接口全限定名一致。(3)XML映射文件中SQL語(yǔ)句的id與Mapper接口中的方法名一致,并保持返回類型一致。13.1.2MyBatis基礎(chǔ)操作案例:使用XML映射配置文件操作數(shù)據(jù)庫(kù)圖

13-1

工程目錄結(jié)構(gòu)13.1.2MyBatis基礎(chǔ)操作(1)創(chuàng)建文件EmpMapper.java@Mapper

publicinterfaceEmpMapper{

publicvoidinsert(Empemp);

publicvoiddelete(Integerid);

publicvoidupdate(Empemp);

publicEmpgetById(Integerid);

publicList<Emp>list(Stringname,Shortgender,LocalDatebegin,LocalDateend);

}(2)創(chuàng)建EmpMapper.xml文件<mappernamespace="com.swxy.mapper.EmpMapper">

<insertid="insert"keyProperty="id"useGeneratedKeys="true">

INSERTINTOemp(username,password,name,gender,image,job,entrydate,dept_id,

create_time,update_time)VALUES(#{username},#{password},#{name},#{gender}, #{image},#{job},#{entrydate},#{deptId},#{createTime},#{updateTime})

</insert>13.1.2MyBatis基礎(chǔ)操作

<deleteid="delete">deletefromempwhereid=#{id}</delete>

<updateid="update">updateempsetusername=#{username},password=#{password},name=#{name},

gender=#{gender},image=#{image},job=#{job},entrydate=#{entrydate},dept_id=#{deptId},create_time=#{createTime},update_time=#{updateTime}

whereid=#{id}

</update>

<selectid="getById"resultType="com.swxy.pojo.Emp">select*fromempwhereid=#{id}

</select>

<selectid="list"resultType="com.swxy.pojo.Emp">

select*fromempwherenamelikeconcat('%',#{name},'%')andgender=#{gender}andentrydatebetween#{begin}and#{end}

</select>

</mapper>13.1.2MyBatis基礎(chǔ)操作(3)編寫(xiě)測(cè)試類@Slf4j@SpringBootTestclassSpringbootMybatisCrudApplicationTests{ @Autowired privateEmpMapperempMapper; @Test voidtestInsert(){ Empemp=newEmp(0,"oky","123456","蔣亞平",(short)1,"1.png",(short)4,LocalDate.of(2021,3,5),2,LocalDateTime.now(),LocalDateTime.now()); ("增加員工"); empMapper.insert(emp); } @Test voidtestDelet(){ ("刪除編號(hào)為{}的員工",18); empMapper.delete(18); }

13.1.2MyBatis基礎(chǔ)操作 @Test voidtestUpdate(){ Empemp=newEmp(19,"chalyabc","123456789","Charles",(short)1,"1.png",(short)4,LocalDate.of(2021,3,5),2,LocalDateTime.now(),LocalDateTime.now()); ("修改員工"); empMapper.update(emp); } @Test voidtestGetById(){ Empemp=empMapper.getById(1); System.out.println(emp); } @Test voidtestList(){ List<Emp>empList=empMapper.list("蔣",(short)1,LocalDate.of(1990,5,6),LocalDate.of(2024,5,9)); System.out.println(empList); }}13.2.2MyBatis動(dòng)態(tài)SQL隨著用戶的輸入或外部條件的變化而變化的SQL語(yǔ)句,我們稱為動(dòng)態(tài)SQL。常用的動(dòng)態(tài)SQL:if、where和set元素

<updateid="update">

updateemp

<set>

<iftest="username!=null">username=#{username},</if>

<iftest="password!=null">password=#{password},</if></set><where> <iftest="name!=null">

name=#{name}

</if><where></update>13.2.2MyBatis動(dòng)態(tài)SQLforeachforeach標(biāo)簽可以用來(lái)遍歷數(shù)組、列表和Map等集合參數(shù),實(shí)現(xiàn)批量操作或一些簡(jiǎn)單SQL操作,foreach元素屬性及作用如下。Collection:集合名稱item:集合遍歷出來(lái)的元素或者項(xiàng)separator:每一次遍歷使用的分隔符open:遍歷開(kāi)始前拼接的片段close:遍歷結(jié)束后拼接的片段案例:根據(jù)員工編號(hào)批量刪除員工數(shù)據(jù)<deleteid="deleteByIds">

deletefromempwhereidin

<foreachcollection="ids"item="id"separator=","open="("close=")">

#{id}

</foreach>

</delete>13.2.2MyBatis動(dòng)態(tài)SQLsql和include元素sql元素用來(lái)定義可重用的SQL片段。include元素通過(guò)屬性refid指定包含的sql片段。案例:根據(jù)員工編號(hào)查詢員工信息<sqlid="commonSelect"> selectid,username,password,name,gender,image,job,entrydate,dept_id,create_time,update_timefromemp</sql><selectid="getById"resultType="com.swxy.pojo.Emp"><includerefid="commonSelect"/>whereid=#{id}</select>13.3分頁(yè)查詢13.3.1傳統(tǒng)方法13.3.2分頁(yè)插件PageHelper13.3.1傳統(tǒng)方法客戶端通過(guò)傳遞頁(yè)碼、每頁(yè)顯示記錄條數(shù),數(shù)據(jù)庫(kù)通過(guò)分頁(yè)函數(shù)進(jìn)行分頁(yè),例如,MySQL使用limit函數(shù),數(shù)據(jù)層需要編寫(xiě)獲取總記錄數(shù)和分頁(yè)查詢二個(gè)方法。(1)創(chuàng)建實(shí)體類PageBean@Data

@NoArgsConstructor

@AllArgsConstructor

publicclassPageBean{

privateLongtotal;

privateListrows;

}(2)編寫(xiě)數(shù)據(jù)層EmpMapper文件@MapperpublicinterfaceEmpMapper{ @Select("selectcount(*)fromemp") publicLongcount(); @Select("select*fromemplimit#{start},#{pageSize}") publicList<Emp>page(Integerstart,IntegerpageSize);}13.3.1傳統(tǒng)方法(3)編寫(xiě)業(yè)務(wù)層實(shí)現(xiàn)類@ServicepublicclassEmpServiceImplimplementsEmpService{ @Autowired privateEmpMapperempMapper; @Override publicPageBeanpage(Integerpage,IntegerpageSize){ Longcount=empMapper.count(); Integerstart=(1)*pageSize; List<Emp>empList=empMapper.page(start,pageSize); PageBeanpageBean=newPageBean(count,empList); returnpageBean; }}13.3.1傳統(tǒng)方法(4)編寫(xiě)控制層@RestControllerpublicclassEmpController{ @Autowired privateEmpServiceempService; @GetMapping("/emps") publicResultpage(@RequestParam(defaultValue="1")Integerpage,@RequestParam(defaultValue="2")IntegerpageSize){ PageBeanpageBean=empService.page(page,pageSize); returnResult.success(pageBean); }}13.3.1傳統(tǒng)方法(5)使用Postman進(jìn)行測(cè)試圖

13-2

分頁(yè)測(cè)試13.3.2分頁(yè)插件PageHelper使用分頁(yè)插件PageHelper進(jìn)行分頁(yè),需要添加分頁(yè)插件的依賴,數(shù)據(jù)層只需查詢所有記錄,PageHelper插件會(huì)根據(jù)所有記錄進(jìn)行分頁(yè),使用起來(lái)比傳統(tǒng)方法更簡(jiǎn)單。使用分頁(yè)插件PageHelper實(shí)現(xiàn)分頁(yè)的具體步驟:(1)添加PageHelper分頁(yè)插件的依賴<dependency>

<groupId>com.github.pagehelper</groupId>

<artifactId>pagehelper-spring-boot-starter</artifactId>

<version>1.4.2</version>

</dependency>(2)編寫(xiě)數(shù)據(jù)層@Mapper

publicinterfaceEmpMapper{

@Select("select*fromemp")

publicList<Emp>list();

//員工信息查詢}13.3.2分頁(yè)插件PageHelper(3)編寫(xiě)業(yè)務(wù)層實(shí)現(xiàn)類@ServicepublicclassEmpServiceImplimplementsEmpService{ @Autowired privateEmpMapperempMapper; @Override

溫馨提示

  • 1. 本站所有資源如無(wú)特殊說(shuō)明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請(qǐng)下載最新的WinRAR軟件解壓。
  • 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請(qǐng)聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁(yè)內(nèi)容里面會(huì)有圖紙預(yù)覽,若沒(méi)有圖紙預(yù)覽就沒(méi)有圖紙。
  • 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
  • 5. 人人文庫(kù)網(wǎng)僅提供信息存儲(chǔ)空間,僅對(duì)用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對(duì)用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對(duì)任何下載內(nèi)容負(fù)責(zé)。
  • 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請(qǐng)與我們聯(lián)系,我們立即糾正。
  • 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時(shí)也不承擔(dān)用戶因使用這些下載資源對(duì)自己和他人造成任何形式的傷害或損失。

評(píng)論

0/150

提交評(píng)論