-
Notifications
You must be signed in to change notification settings - Fork 0
1.注册Mapper接口
FuriousPws002 edited this page Apr 3, 2024
·
1 revision
代码分支:01-regist-mapper
Mapper注册由MapperRegistry类实现,该类中用一个Map存储了mybatis中所有注册的Mapper,key为Mapper的接口,value为MapperProxyFactory的代理工厂类,核心代码如下
public class MapperRegistry {
private final Map<Class<?>, MapperProxyFactory<?>> knownMappers = new HashMap<>();
public <T> void addMapper(Class<T> type) {
knownMappers.put(type, new MapperProxyFactory<>(type));
}
public <T> T getMapper(Class<T> type, SqlSession sqlSession) {
MapperProxyFactory<?> mapperProxyFactory = knownMappers.get(type);
if (Objects.isNull(mapperProxyFactory)) {
throw new BindingException(type + " type is not exist");
}
return mapperProxyFactory.newInstance(sqlSession);
}
}
单元测试:
public class MapperRegistryTest {
@Test
public void test() {
Configuration configuration = new Configuration();
configuration.addMapper(UserMapper.class);
SqlSession sqlSession = new DefaultSqlSession(configuration);
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
Assert.assertNotNull(userMapper);
}
}