项目上报了个奇怪的错,关于 mybatis 的
The alias '' is already mapped to the value 'cn.cceking.blog.novel.model.dto.Article$1'
详细异常信息如下
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sqlSessionFactory' defined in class path resource [tk/mybatis/mapper/autoconfigure/MapperAutoConfiguration.class]:
Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException:
Failed to instantiate [org.apache.ibatis.session.SqlSessionFactory]: Factory method 'sqlSessionFactory' threw exception;
nested exception is org.apache.ibatis.type.TypeException: The alias '' is already mapped to the value 'cn.cceking.blog.novel.model.dto.Article$1'.
一般而言,这个异常的出现是存在同名类导致的,也就是包名和类名一样,这个可能在引入不同的 jar 存在同名类导致的。
但项目中的可不一样,无论我用 IDEA 怎么搜,都没发现同名类,而且重复的别名 alias 是 ‘’ 。
排查
debug 源码,异常的源头在 TypeAliasRegistry 这个类下的 registerAlias 方法,在 mybatis 初始化注册的时候存在重复的别名 “”
public void registerAlias(Class<?> type)
经过一步步 debug 排查,终于找到问题了,是实体类中的匿名类 TypeReference 导致的。
实体类中存在两个匿名类,而匿名类默认都是别名都是 “” 这个空字符串,冲突导致的。
相关代码如下(类似)
public void getContent() throws JsonProcessingException {
ObjectMapper objectMapper = new ObjectMapper();
String foo1 = objectMapper.readValue(url, new TypeReference<String>() {
});
Integer foo2 = objectMapper.readValue(url, new TypeReference<Integer>() {
});
}
解决方法
声明匿名类,或者