Spring boot整合mybatis实现过程图解

网友投稿 453 2023-05-03

Spring boot整合mybatis实现过程图解

Spring boot整合mybatis实现过程图解

导入mybatis jar包

右键pom.xml

模拟springboot底层实现类

1.

定义接口

@Mapper

public interface GoodsDao {

/**

* 基于商品id删除商品

* @param id 商品id

* @return 删除行数

* 数据层方法对象的sql映射

*/

@Delete("delete from tb_goods where id=#{id}")

//当传入的参数只有一个且不是数组时

//#{id}这个地方的变量可以不是传入的参数名(自己随意)

int deleteById(Integer id);

}

测试

@SpringBootTest

public class TestGoods {

@Autowired

private GoodsDao gd;

@Test

void TestGoods() {

int i =gd.deleteById(10);

System.out.println(i);

}

}

2.

自己实现

接口方法

@Mapper

public interface GoodsDao {

/**

* 基于商品id删除商品

* @param id 商品id

* @return 删除行数

* 数据层方法对象的sql映射

*/

@Delete("delete from tb_goods where id=#{id}")

int deleteById(Integer id);

}

@Component

public class GoodsDaoImpl {

@IreNTsxdirAutowired

private 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)

}

}

@SpringBootTest

public class GoodsDaoImpTest {

@Autowired

private IreNTsxdirGoodsDaoImpl gdi;

@Test

void 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头文件(去官网)

PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"

"http://mybatis.org/dtd/mybatis-3-mapper.dtd">

delete from tb_goods

id in

item="i">

#{i}

item="i">

#{i}

or 1=2

配置

测试:

@Autowired

private GoodsDao gd;

@Test

void deleteObject() {

int rows=gd.deleteObject(1,2,3);

System.out.println(row);

}

当我们在执行此方法时,其实现类内部会检测接口方法上是否有定义sql映射

假如没有,然后基于接口类全名找到对应的映射文件(mapper映射文件的id),然后在基于方法名

再找到对应映射文件的元素,进而获取sql映射

错误解决:

binding异常还有可能时参数异常,还有可能是配置文件有问题

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:阿里云OSS域名配置及简单上传的示例代码
下一篇:IDEA遇到Internal error. Please refer to http://jb. gg/ide/critical
相关文章

 发表评论

暂时没有评论,来抢沙发吧~