Spring boot整合mybatis實現過程圖解
導入mybatis jar包
右鍵pom.xml
模擬springboot底層實現類
1.
定義接口
@Mapperpublic interface GoodsDao {/** * 基于商品id刪除商品 * @param id 商品id * @return 刪除行數 * 數據層方法對象的sql映射 */ @Delete('delete from tb_goods where id=#{id}') //當傳入的參數只有一個且不是數組時 //#{id}這個地方的變量可以不是傳入的參數名(自己隨意) int deleteById(Integer id);}
測試
@SpringBootTestpublic class TestGoods {@Autowiredprivate GoodsDao gd;@Testvoid TestGoods() {int i =gd.deleteById(10);System.out.println(i);}}
2.
自己實現
接口方法
@Mapperpublic interface GoodsDao {/** * 基于商品id刪除商品 * @param id 商品id * @return 刪除行數 * 數據層方法對象的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);}}
直接導mapper文件找對應的元素
3.
當sql語句比較復雜時使用映射文件
接口:
/** *GoodsDao.java * ids可以接受多個參數 * 在mapper文件中直接使用array來接受, * @param ids * @return */ int deleteObject(/*@Param('ids')*/Integer...ids); //當mybatis過低時需要加上@Param('ids')才能識別
不加@Param('ids')報錯
使用xml映射
獲取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='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>
配置:
測試:
@Autowiredprivate GoodsDao gd;@Testvoid deleteObject() {int rows=gd.deleteObject(1,2,3);System.out.println(row);}
當我們在執行此方法時,其實現類內部會檢測接口方法上是否有定義sql映射
假如沒有,然后基于接口類全名找到對應的映射文件(mapper映射文件的id),然后在基于方法名
再找到對應映射文件的元素,進而獲取sql映射
錯誤解決:
binding異常還有可能時參數異常,還有可能是配置文件有問題
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持好吧啦網。
相關文章: