Mybatis报错 Cause: org.apache.ibatis.type.TypeException: Could not resolve type alias 'UserEntity'

1年多没用Mybatis,闲来无事去官网照着文档单独配置个MyBatis跑着玩玩,结果不是很顺利。

1.报错原因

 The error may exist in mapper/UserMapper.xml
### Cause: org.apache.ibatis.builder.BuilderException: Error parsing SQL Mapper Configuration. Cause: org.apache.ibatis.builder.BuilderException: Error parsing Mapper XML. The XML location is 'mapper/UserMapper.xml'. Cause: org.apache.ibatis.builder.BuilderException: Error resolving class. Cause: org.apache.ibatis.type.TypeException: Could not resolve type alias 'UserEntity'.  Cause: java.lang.ClassNotFoundException: Cannot find class: UserEntity
	at org.apache.ibatis.exceptions.ExceptionFactory.wrapException(ExceptionFactory.java:30)
	at org.apache.ibatis.session.SqlSessionFactoryBuilder.build(SqlSessionFactoryBuilder.java:80)
	at org.apache.ibatis.session.SqlSessionFactoryBuilder.build(SqlSessionFactoryBuilder.java:64)
	at com.danielei.config.SqlSessionConfig.sqlSessionFactory(SqlSessionConfig.java:15)
	at com.danielei.Test.main(Test.java:17)

2.Mapper文件配置如下

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.danielei.dao.UserDao">

    <select id="selectUser" resultType="UserEntity">
    select user_id,username from tb_user
    </select>
</mapper>

报错原因是这个 resultType=“UserEntity”找不到,Mybatis解析的时候出错,找不到对应的类。

查找了一下源码,发现是没有配置typeAliases,也就是mybatis-config.xml中没有这个标签。

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <typeAliases>
        <package name="com.danielei.entity"></package>
    </typeAliases>
       省略其它。。。
</configuration>

这个标签的作用是扫描指定包下面的实体类,对只是这个包下的实体类,因为Mybatis用endsWith(".class")判断是否.class文件名结尾的,Mybatis会把这些实体类注册进去,说白了就是放在一个HashMap中 put进去,key默认是小写原类名(userentity)mybatis转换为小写的,value就是UserEntity的实例。
还在源码中看到 如果在实体类中加入@Alias(“customUser”)那么注册的实体类名就是这个自定义的名称。
如图
 图中可看到,UserEntity别名为customUser 那是因为我在实体类注解中加了@Alias("customUser")
不加@Alias那么默认就是类名userentity
为什么resultType:只需要打上实体类的名称就能用了,那是因为Mybatis底层解析mybatis-config.xml根据你的typeAliases配置去扫描了包,并放在了一个HashMap中key为类名(Mybatis会把类名转为小写)value就是类实例,如果不配置typeAliase打上简单类名,然后Mybatis去Map中找是否有这个key,如果没有那么就反射实例出来,因为不是完整包路径+类名所以反射实例类就会提示找不到UserEntity,必须是完整包路径+类名。
总结:
1.mybatis-config.xml中配置typeAliases 扫描实体类包路径,Mapper.xml中resultType属性可以打简单类名。
2.没在mybatis-config.xml配置typeAliases那么Mapper.xml中resultType请改为 包路径+类名,就是这么简单。

  • 10
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值