每次使用Mybatis的时候都是去网上百度一下,然后照着网上的文章一步一步在自己的IDEA中进行配置,但是有时候明明是按着人家跑起来的流程配置的,但是就是不知道啥原因,有时就跑的起来,有时又不行!现在记录下自己粗心时碰到的情况,以便自己下次能够定位碰到过的问题。
第一种:Mapper.xml文件中的sql查询语句有错误
<mapper namespace="com.mybatis.demo.dao.UserMapper">
<select id="getUserById" parameterType="Integer" resultType="com.mybatis.demo.entity.User">
select * from user where id=#{id}
</select>
</mapper>
有一次是从其他项目复制的代码,然后上面配置中 resultType类型错误,导致了未知的错误。
第二种:启动类上未配置@MapperScan({"***.***.***"})
MapperScan中的basePackages的值对应的是***Mapper接口文件所在位置。
当未配置此注解时,会出现如下错误:
No MyBatis mapper was found in '[com.mybatis.demo]' package. Please check your configuration.
Field userMapper in com.mybatis.demo.service.impl.UserServiceImpl required a bean of type 'com.mybatis.demo.dao.UserMapper' that could not be found.
The injection point has the following annotations:
- @org.springframework.beans.factory.annotation.Autowired(required=true)
Action:
Consider defining a bean of type 'com.mybatis.demo.dao.UserMapper' in your configuration.
第三种:target文件夹下未生成对应的代码
properties.application中有如下配置:
mybatis.mapper-locations=classpath:com/mybatis/demo/mapper/*.xml
项目目录如下:
点击运行按钮之后,生成的target文件夹如下:
可以看到,此时的目录下并没有mapper文件夹,不知道是什么导致的问题。此时测试语句会有如下错误:
org.apache.ibatis.binding.BindingException: Invalid bound statement (not found): com.mybatis.demo.dao.UserMapper.getUserById
解决办法:将src目录下的mapper文件夹复制到target文件夹下的相同位置。然后重新启动项目。这时的target目录下是有mapper文件夹的。如下图:
另一种推荐的mapper放置方式:将mapper文件夹放置到resources下面。
properties.application中配置如下:
mybatis.mapper-locations=classpath:mapper/*.xml
classpath: 这个前缀可加可不加。
再点击run运行项目,此时生成的target目录如下:
可以看到IDEA中的target下是自动生成了mapper的。