Spring boot整合mybatis實(shí)現(xiàn)過(guò)程圖解
導(dǎo)入mybatis jar包
右鍵pom.xml
模擬springboot底層實(shí)現(xiàn)類(lèi)
1.
定義接口
@Mapperpublic interface GoodsDao {/** * 基于商品id刪除商品 * @param id 商品id * @return 刪除行數(shù) * 數(shù)據(jù)層方法對(duì)象的sql映射 */ @Delete('delete from tb_goods where id=#{id}') //當(dāng)傳入的參數(shù)只有一個(gè)且不是數(shù)組時(shí) //#{id}這個(gè)地方的變量可以不是傳入的參數(shù)名(自己隨意) int deleteById(Integer id);}
測(cè)試
@SpringBootTestpublic class TestGoods {@Autowiredprivate GoodsDao gd;@Testvoid TestGoods() {int i =gd.deleteById(10);System.out.println(i);}}
2.
自己實(shí)現(xiàn)
接口方法
@Mapperpublic interface GoodsDao {/** * 基于商品id刪除商品 * @param id 商品id * @return 刪除行數(shù) * 數(shù)據(jù)層方法對(duì)象的sql映射 */ @Delete('delete from tb_goods where id=#{id}') int deleteById(Integer id);}
@Componentpublic class GoodsDaoImpl {@Autowiredprivate SqlSession sqlSession; public int deleteById(Integer id) {return sqlSession.delete('com.cy.demo.goods.dao.GoodsDao.deleteById', id);//sqlSession.delete('com.cy.demo.goods.dao.deleteById',id)}}
@SpringBootTestpublic class GoodsDaoImpTest {@Autowiredprivate GoodsDaoImpl gdi;@Testvoid testdelete() {int i = gdi.deleteById(9);System.out.println(i);}}
直接導(dǎo)mapper文件找對(duì)應(yīng)的元素
3.
當(dāng)sql語(yǔ)句比較復(fù)雜時(shí)使用映射文件
接口:
/** *GoodsDao.java * ids可以接受多個(gè)參數(shù) * 在mapper文件中直接使用array來(lái)接受, * @param ids * @return */ int deleteObject(/*@Param('ids')*/Integer...ids); //當(dāng)mybatis過(guò)低時(shí)需要加上@Param('ids')才能識(shí)別
不加@Param('ids')報(bào)錯(cuò)
使用xml映射
獲取xml頭文件(去官網(wǎng))
<?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.cy.demo.goods.dao.GoodsDao'><delete id='deleteObject'>delete from tb_goods<where><if test='ids!=null and ids.length>0'>id in<foreach collection='ids' open='(' close=')' separator=','item='i'>#{i}</foreach></if>or 1=2</where></delete></mapper>
配置:
測(cè)試:
@Autowiredprivate GoodsDao gd;@Testvoid deleteObject() {int rows=gd.deleteObject(1,2,3);System.out.println(row);}
當(dāng)我們?cè)趫?zhí)行此方法時(shí),其實(shí)現(xiàn)類(lèi)內(nèi)部會(huì)檢測(cè)接口方法上是否有定義sql映射
假如沒(méi)有,然后基于接口類(lèi)全名找到對(duì)應(yīng)的映射文件(mapper映射文件的id),然后在基于方法名
再找到對(duì)應(yīng)映射文件的元素,進(jìn)而獲取sql映射
錯(cuò)誤解決:
binding異常還有可能時(shí)參數(shù)異常,還有可能是配置文件有問(wèn)題
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. 解決ajax的delete、put方法接收不到參數(shù)的問(wèn)題方法2. JavaScript實(shí)現(xiàn)組件化和模塊化方法詳解3. PHP字符串前后字符或空格刪除方法介紹4. html清除浮動(dòng)的6種方法示例5. 使用AJAX(包含正則表達(dá)式)驗(yàn)證用戶(hù)登錄的步驟6. Python基于Serializer實(shí)現(xiàn)字段驗(yàn)證及序列化7. PHP循環(huán)與分支知識(shí)點(diǎn)梳理8. ASP基礎(chǔ)入門(mén)第三篇(ASP腳本基礎(chǔ))9. JSP之表單提交get和post的區(qū)別詳解及實(shí)例10. css進(jìn)階學(xué)習(xí) 選擇符
