一、常见问题
1、org.apache.ibatis.binding.BindingException: Invalid bound statement (not found)
无法找到绑定mapper.xml文件
问题分析思路:这个问题主要是由mapper接口配置和mapper.xml文件导致的,可以从以下几个方面检查
1) xml中的namespace命名与mapper接口全限定类名是否一致;
2)mapper.xml文件路径是否正确,application.properties中配置了mapper的文件路径:
mybatis.mapper-locations=classpath:mapper/*.xml
注意:如果mapper.xml与mapper接口放在一起,无需添加上述配置
3)mapper.xml文件是否放置到src/main/resources下面,没有的话,将不会被maven build plugin给默认扫描到,修改pom.xml文件
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
</resource>
</resources>
</build>
2、查询语句映射结果集不匹配 Could not resolve type alias ‘xxxMap’
1)查看结构集接收类型使用的是resultType和resultMap,resultType中使用的pojo类名,此时对象字段名要与表结构的row一致,不然无法映射对象,导致查询sql查到数据,但是接口返回对象为空。
2)resultMap配置时,type字段一定要匹配上,不要多个空格什么的,笔者就在这里踩到了,使用mybatis提供的generator插件生成mapper.xml文档时,在generatorConfig.xml中配置错了,javaModelGenerator 中配置包路径多了一个空格,导致映射出错,无法找到类文件
<!-- 生成模型的包名和位置-->
<!-- 多了空格-->
<javaModelGenerator targetPackage=" com.demo.pojo.User" targetProject="src/main/java">
</javaModelGenerator>
<resultMap id="User" type=" com.demo.pojo.User"><!-- 多了空格-->
<id column="userid" property="userid" javaType="int" ></id>
<result column="username" property="username" javaType="String" ></result>
</resultMap>
3、插入语句中存在空值
当列中存在空值时,必须指定参数对象的类型
JDBC 要求,如果一个列允许使用 null 值,并且会使用值为 null 的参数,就必须要指定 JDBC 类型(jdbcType)
对于插入以及跟新语句,如果字段存在空值时,建议使用动态sql语句,
insert into websites
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="name != null">
name,
</if>
...
</trim>
update websites
<set>
<if test="name != null">
name =#{name,jdbcType=VARCHAR},
</if>
...
</set>
4、参数为集合对象映射处理
使用动态sql语句foreach对集合进行遍历
你可以将任何可迭代对象(如 List、Set 等)、Map 对象或者数组对象作为集合参数传递给 foreach。当使用可迭代对象或者数组时,index 是当前迭代的序号,item 的值是本次迭代获取到的元素。当使用 Map 对象(或者 Map.Entry 对象的集合)时,index 是键,item 是值。