-
If you use the Mapper mapper, how do you only need to write the interface, without writing the implementation, the framework is automatically generated
-
Specification:
2.1 Traditional Dao interface, now the name ends with Mapper: For example: IUserDao-> UserMapper
2.2 Put UserMapper interface and mapping file UserMapper.xml in cn.itsource.mapper -
Implementation steps:
3.1. Create a new package cn.itsource.mapper, create a new interface [ProductMapper] in the package and
directly go to IProductDao to copy
3.2. In package cn.itsource.mapper, create a new mapping file [ProductMapper.xml] The content is copied to the xml in the domain package, and the namespace is modified to cn.itsource.mapper.ProductMapper
3.3. Load the mapper mapping file in the main configuration file -
Functional test: query a single object:
SqlSession session = MybatisUtil.getSession();
//接口不能实例化 -- 框架帮我们实现了的(只不过不需要去管怎么实现,甚至你连实现类的名字都不知道),然后通过多态的方式进行接收
ProductMapper mapper = session.getMapper(ProductMapper.class);//获取接口的代理对象
System.out.println(mapper.loadOne(1l));
5. Modify:
@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);
}