Spring boot整合mybatis的方法
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异常还有可能时参数异常,还有可能是配置文件有问题
感谢各位的阅读!看完上述内容,你们对Spring boot整合mybatis的方法大概了解了吗?希望文章内容对大家有所帮助。如果想了解更多相关文章内容,欢迎关注亿速云行业资讯频道。
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。