最近用Mybatis 缓存时发现 @CacheNamespaceRef的用法让我无语
两个mapper
@Mapper
@CacheNamespace
public interface BreedBaseMapper {
}
@Mapper
@CacheNamespaceRef(BreedBaseMapper.class)
public interface TestMapper {
}
首先如果我没用错的话.
然后遇到了在使用时报错, TestMapper 始终先加载,改了顺序无效, 让其在更深层次的包中也无效.
@Autowired
BreedBaseMapper bbm;
@Autowired
TestMapper tm;
这就导致了报错
MapperAnnotationBuilder.java 部分源码
public void parse() {
String resource = type.toString();
if (!configuration.isResourceLoaded(resource)) {
loadXmlResource();
configuration.addLoadedResource(resource);
assistant.setCurrentNamespace(type.getName());
parseCache();
parseCacheRef();
Method[] methods = type.getMethods();
for (Method method : methods) {
try {
// issue #237
if (!method.isBridge()) {
parseStatement(method);
}
} catch (IncompleteElementException e) {
configuration.addIncompleteMethod(new MethodResolver(this, method));
}
}
}
parsePendingMethods();
}
从中先是转换缓存再转换引用
然而第一个调用此方法的是 TestMapper
引发了异常
private void parseCacheRef() {
CacheNamespaceRef cacheDomainRef = type.getAnnotation(CacheNamespaceRef.class);
if (cacheDomainRef != null) {
Class<?> refType = cacheDomainRef.value();
String refName = cacheDomainRef.name();
if (refType == void.class && refName.isEmpty()) {
throw new BuilderException("Should be specified either value() or name() attribute in the @CacheNamespaceRef");
}
if (refType != void.class && !refName.isEmpty()) {
throw new BuilderException("Cannot use both value() and name() attribute in the @CacheNamespaceRef");
}
String namespace = (refType != void.class) ? refType.getName() : refName;
assistant.useCacheRef(namespace);
}
}
由于调用此方法的时候是 TestMapper, 从而获取到了
@CacheNamespaceRef(BreedBaseMapper.class)
指向的namespace “com.xx.mybatis.mappers.single.BreedBaseMapper” 的类全名
又调用 useCacheRef(namespace) 方法
public Cache useCacheRef(String namespace) {
if (namespace == null) {
throw new BuilderException("cache-ref element requires a namespace attribute.");
}
try {
unresolvedCacheRef = true;
Cache cache = configuration.getCache(namespace);
if (cache == null) {
throw new IncompleteElementException("No cache for namespace '" + namespace + "' could be found.");
}
currentCache = cache;
unresolvedCacheRef = false;
return cache;
} catch (IllegalArgumentException e) {
throw new IncompleteElementException("No cache for namespace '" + namespace + "' could be found.", e);
}
}
而 通过这各namespace 调用 getCache() 然而BreedBaseMapper还没被添加到缓存集合中
继而抛出异常
if (cache == null) {
throw new IncompleteElementException("No cache for namespace '" + namespace + "' could be found.");
}
没耐心去找原因了, 花了一两小时没找到 脑壳痛 XML方式没试过,此为注解方式遇到的问题.