导入mybatis jar包
右键pom.xml
模拟springboot底层实现类
1.
定义接口
@Mapper
public interface GoodsDao {
@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 {
@Delete("delete from tb_goods where id=#{id}")
int deleteById(Integer id);
}
@Component
public class GoodsDaoImpl {
@Autowired
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 GoodsDaoImpl gdi;
@Test
void testdelete() {
int i = gdi.deleteById(9);
System.out.println(i);
}
}
直接导mapper文件找对应的元素
3.
当sql语句比较复杂时使用映射文件
接口:
int deleteObject(Integer...ids);
//当mybatis过低时需要加上@Param("ids")才能识别
不加@Param("ids")报错
使用xml映射
获取xml头文件(去官网)
delete from tb_goods id in or 1=2#{i}
配置:
测试:
@Autowired
private GoodsDao gd;
@Test
void deleteObject() {
int rows=gd.deleteObject(1,2,3);
System.out.println(row);
}
当我们在执行此方法时,其实现类内部会检测接口方法上是否有定义sql映射
假如没有,然后基于接口类全名找到对应的映射文件(mapper映射文件的id),然后在基于方法名
再找到对应映射文件的元素,进而获取sql映射
错误解决:
binding异常还有可能时参数异常,还有可能是配置文件有问题
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持考高分网。



