之前我们尝试了,如何创建一个映射器来将结果快速转换为实体类,但我们每次都需要去找映射器对应操作的名称,而且还要知道对应的返回类型,再通过SqlSession
来执行对应的方法,能不能再方便一点呢?
通过namespace
来绑定到一个接口上,利用接口的特性,我们可以直接指明方法的行为,而实际实现则是由Mybatis来完成。
public interface TestMapper {
List<Student> selectStudent();
}
接着更改在TestMapper.xml中设置的namespace路径,改成当前的包装器接口:
<mapper namespace="TestMapper">
同时我们也可以把TestMapper.xml文件移动到resources文件夹中:
<mappers>
<mapper resource="mappers/TestMapper.xml"/>
</mappers>
最后就可以通过创建接口 TestMapper
来获取需要的方法:
TestMapper testMapper = sqlSession.getMapper(TestMapper.calss);
List<Student> student = testMapper.selectStudent();
student.forEach(System.out::println);
这里之所以能直接获得实现类,是因为 Mybatis 通过动态代理生成了一个类型为 com.sun.proxy.$Proxy4
的实现类。