1. 传统开发
编写接口,实现,测试
2. 代理开发
Mapper 接口开发方法只需要程序员编写Mapper 接口(相当于Dao 接口),由Mybatis 框架根据接口定义创建接口的动态代理对象,代理对象的方法体同上边Dao接口实现类方法。
Mapper 接口开发需要遵循以下规范:
-
Mapper.xml文件中的namespace与mapper接口的全限定名相同
-
Mapper接口方法名和Mapper.xml中定义的每个statement的id相同
Mapper.xml中
- Mapper接口方法的输入参数类型和mapper.xml中定义的每个sql的parameterType的类型相同
- Mapper接口方法的输出参数类型和mapper.xml中定义的每个sql的resultType的类型相同
测试实现
用代理实现
public static void main(String[] args) throws IOException {
InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
SqlSession openSession = sqlSessionFactory.openSession();
//不同之处
UserMapper mapper = openSession.getMapper(UserMapper.class);
List<User> all = mapper.findAll();
System.out.println(all);
}
用传统开发实现(比较)
public void test1() throws IOException {
InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml");
SqlSessionFactoryBuilder().build(resourceAsStream);
SqlSession openSession = sqlSessionFactory.openSession();
//不同之处
List<User> userList = openSession.selectList("userMapper.findAll");
System.out.println(userList);
openSession.close();
}