通常mybatis的操作步驟:
1.SqlSession sqlSession = DBUtil.getSessionFactory().openSession();
System.out.println(sqlSession.getClass().getName());//org.apache.ibatis.session.defaults.DefaultSqlSession
2.UserDao userDao = sqlSession.getMapper(UserDao.class);
3.User u = userDao.selectUserById(1);
那么UserDao userDao = sqlSession.getMapper(UserDao.class)是怎么得到的?以及如何和xml定義的查詢方法關(guān)聯(lián)起來的幔嫂?
具體主要流程步驟:
首先加載配置文件mybatis-config.xml => UserMapper.xml
當(dāng)加載到UserMapper.xml文件時黔宛,通過namespace="mybatis.demo.dao.UserDao" 創(chuàng)建UserDao對象,并且UserDao對象以key的方式放到MapperRegistry(mapper注冊器)中(見名知意),
那么既然有key,value傳入的是什么呢?通過查看源碼翼抠,value是一個UserDao的代理對象,且實(shí)現(xiàn)了UserDao接口获讳;
源碼:
final MapperProxyFactory mapperProxyFactory = (MapperProxyFactory)knownMappers.get(type);
if (mapperProxyFactory == null)
???? throw new BindingException("Type " + type + " is not known to the MapperRegistry.");
try {
??? return mapperProxyFactory.newInstance(sqlSession);
} catch (Exception e) {
??? throw new BindingException("Error getting mapper instance. Cause: " + e, e);
}
mapperProxyFactory:mapper代理工廠阴颖,生成的對象就是代理對象;
至于MapperRegistry對象里面的value為什么是代理對象且實(shí)現(xiàn)了UserDao接口赔嚎?
UserDao userDao = sqlSession.getMapper(UserDao.class);
userDao該對象通過debug可得知為:org.apache.ibatis.binding.MapperProxy@5c5eefef類型膘盖,既然能用UserDao接收,所以應(yīng)該實(shí)現(xiàn)了UserDao接口尤误;
UserMapper.xml的作用:
通過該文件可以生成一個實(shí)現(xiàn)了UserDao接口的代理對象侠畔;并把UserDao對象當(dāng)做key,代理對象當(dāng)做value放到MapperRegistry中损晤;