1.问题

org.apache.ibatis.binding.BindingException: Invalid bound statement (not found)

Springboot项目中,在mybatis中mapper数据库操作接口(有的称DAO,有的直接说mapper,都只同一文件)与mapper配置文件在做映射绑定的时候出现问题,简单说,就是接口与xml要么是找不到,要么是找到了却匹配不到。

2.原因导致 Invalid bound statement (not found)的可能原因有:

1)xml文件所在package名称和mapper interface所在的package name不一致,mapper 的namespace写的不对,需要修改。

mapper映射的xml文件示例:

<?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.example.demo.mapper.IDemoMapper">

</mapper>

2)  mapper 接口文件在映射的xml文件中没有,执行对应方法后报 Invalid bound statement (not found)。

 <delete id="deleteBannerById">
       DELETE FROM banner WHERE banner_id=#{bannerId};
 </delete>

delete标签的id名与mapper接口中的方法名保持一致,即一摸一样;

#{  }占位符内变量名与接口文件中方法传进来的参数名保持一致。

3)mapper接口文件中的返回值为定义的POJO时,select元素中没有正确配置ResultMap,或者只配置了ResultType

<select id="getBannerById" resultMap="GetBannersMap">
        SELECT <include refid="BannersQueryFields"></include>
        FROM banner
        WHERE banner_id=#{bannerId}
<select>

<resultMap id="GetBannersMap" type="com.example.demo.pojo.vo.BannerVO">
        <id column="banner_id" property="bannerId"></id>
        <result column="img_url" property="imgUrl"></result>
        <result column="a_href" property="abnHref"></result>
        <result column="is_use" property="isUse"></result>
        <result column="need_href" property="needHref"></result>
        <result column="need_imgurl" property="needImgUrl"></result>
        <result column="add_datetime" property="addDatetime"></result>
</resultMap>

<sql id="BannersQueryFields">
       banner_id,img_url,a_href,is_use,need_href,need_imgurl,add_datetime
</sql>

 select元素中resultMap属性名在xml文件中有对应的resultMap元素,且元素的id与select元素的resultMap属性保持一致。

resultMap的type类型为POJO类路径,需配置正确。

4)xml文件文件名不对,后缀名不是xml,有的时候新建了个不是xml的文件,写好内容后,文件后缀名忘记修改。

5)mapper的xml文件配置路径不正确。SpringBoot要扫描到mapper静态资源文件即xml文件,需要添加配置类

@Configuration
@MapperScan("com.example.demo.mapper")
public class MyBatisConfiguration {
}

@MapperScan注解里的路径不对会出问题,mapper在resource资源夹下,resource在字节码文件中并不存在,mapper是与.java文件同级的。

文件目录示例:

 

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐