-
如果使用了Mapper映射器之后,怎么只需要写接口,不需要写实现,框架自动生成
-
规范:
2.1 传统Dao接口,现在名称统一以Mapper结尾:例如:IUserDao --> UserMapper
2.2 将UserMapper接口和映射文件UserMapper.xml放在cn.itsource.mapper中 -
实现步骤 :
3.1.新建包cn.itsource.mapper,在包中新建一个接口【ProductMapper】
里面的内容直接去IProductDao去复制
3.2.在包cn.itsource.mapper中,新建映射文件【ProductMapper.xml】里面的内容去domain包中xml中复制,修改命名空间namespace为cn.itsource.mapper.ProductMapper
3.3.在主配置文件中加载mapper映射文件 -
功能测试:查询单个对象:
SqlSession session = MybatisUtil.getSession();
//接口不能实例化 -- 框架帮我们实现了的(只不过不需要去管怎么实现,甚至你连实现类的名字都不知道),然后通过多态的方式进行接收
ProductMapper mapper = session.getMapper(ProductMapper.class);//获取接口的代理对象
System.out.println(mapper.loadOne(1l));
5.修改:
@Test
public void testUpdate(){
SqlSession session = MybatisUtil.getSession();
ProductMapper mapper = session.getMapper(ProductMapper.class);
Product old = mapper.loadOne(1l);
System.out.println("更新之前:" + old);
old.setProductName("AD钙奶");
mapper.update(old);
session.commit();//提交事务
Product now = mapper.loadOne(1l);
System.out.println("更新之后:" + now);
}