文章目录
前言
mybatis有三种使用方式,除了在上一篇博文中的基于xml文件的方式,还有今天要总结的接口代理、基于注解的方式。
一、接口代理
1、创建一个xml文件,并在全局配置文件中添加该映射文件:


注:与传统基于xml文件不同的是,这里作用域的名字更改为接口
2、创建一个接口:

注:接口中的方法必须和xml文件中的方法名相同
3、测试代码展示:与传统基于xml文件在使用上的区别:
@Test
public void insert2(){
logs();
SqlSession sqlSession = getSqlSession();
GoodsTest mapper = sqlSession.getMapper(GoodsTest.class);
HashMap<Object, Object> objectObjectHashMap = new HashMap<>();
objectObjectHashMap.put("name","灯具");
objectObjectHashMap.put("goods_num",20);
int i = mapper.insert2(objectObjectHashMap);
sqlSession.commit();
System.out.println("i = " + i);
}
@Test
public void delete2(){
logs();
SqlSession sqlSession = getSqlSession();
GoodsTest mapper = sqlSession.getMapper(GoodsTest.class);
int i = mapper.delete2(11);
sqlSession.commit();
System.out.println("i = " + i);
}
@Test
public void update2(){
logs();
SqlSession sqlSession = getSqlSession();
GoodsTest mapper = sqlSession.getMapper(GoodsTest.class);
int i = mapper.update2();
sqlSession.commit();
System.out.println("i = " + i);
}
@Test
public void selectAll2(){
logs();
SqlSession sqlSession = getSqlSession();
GoodsTest mapper = sqlSession.getMapper(GoodsTest.class);
List<Goods> goods = mapper.selectAll2();
for(Goods g : goods){
System.out.println(g);
}
}
需要sqlSession对象调用getmapper方法,通过反射把接口放进去;然后通过mapper对象再调用方法id名。
二、基于注解
1、创建一个接口:

2、添加接口信息:

3、代码展示:
@Test
public void findAll(){
logs();
SqlSession sqlSession = getSqlSession();
AnnotationDao mapper = sqlSession.getMapper(AnnotationDao.class);
List<House> all = mapper.findAll();
for(House h : all){
System.out.println(h);
}
}
@Test
public void findOne(){
logs();
SqlSession sqlSession = getSqlSession();
AnnotationDao mapper = sqlSession.getMapper(AnnotationDao.class);
House one = mapper.findOne(15);
System.out.println(one);
}
@Test
public void insert(){
logs();
SqlSession sqlSession = getSqlSession();
AnnotationDao mapper = sqlSession.getMapper(AnnotationDao.class);
House house = new House();
house.setName("问天");
house.setTel("987");
house.setAddress("云南");
house.setRent("4000");
house.setState("1");
mapper.insert(house);
sqlSession.commit();
sqlSession.close();
}
@Test
public void update(){
logs();
SqlSession sqlSession = getSqlSession();
AnnotationDao mapper = sqlSession.getMapper(AnnotationDao.class);
House house = new House();
house.setName("问雅");
house.setId(15);
mapper.update(house);
sqlSession.commit();
sqlSession.close();
}
@Test
public void delete(){
logs();
SqlSession sqlSession = getSqlSession();
AnnotationDao mapper = sqlSession.getMapper(AnnotationDao.class);
mapper.delete(13);
sqlSession.commit();
sqlSession.close();
}
}
该种方式在使用上和接口代理很相似,但不需要创建xml文件,不将sql语句写在xml文件里而是直接写在接口中的注解里,适用于sql语句少且简单的情况。
3216

被折叠的 条评论
为什么被折叠?



