SpringBoot中使用Mybatis碰到的问题记录

本文记录了在使用Mybatis过程中遇到的配置问题及其解决方案。包括Mapper.xml中的SQL查询错误,启动类缺少@MapperScan注解,以及target目录下未生成Mapper文件。解决方法涉及检查SQL语法,配置@MapperScan注解,以及确认mapper文件的位置。确保正确配置,避免常见的Mybatis配置陷阱。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

每次使用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的。 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值