在使用Mybatisplus时报错Invalid bound statement (not found),在此记录一下
step 1、启动类加上@MapperScan注解
package com.study.test;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@MapperScan(basePackages = {"com.study.*.dao","com.study.*.mapper"})
@SpringBootApplication
public class UaaMain {
public static void main(String[] args) {
SpringApplication.run(UaaMain.class, args);
}
}
step 2、
pom.xml配置中指定resource资源路径
<build>
<resources>
<resource>
<directory>src/main/javadirectory>
<filtering>falsefiltering>
<includes>
<include>**/*.xmlinclude>
includes>
resource>
<resource>
<directory>src/main/resourcesdirectory>
<filtering>falsefiltering>
<includes>
<include>**/*include>
includes>
resource>
resources>
build>
@MapperScan ---- 用于扫描指定路径下的Mapper文件
package com.study.test;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@MapperScan(basePackages = {"com.study.*.dao","com.study.*.mapper"})
@SpringBootApplication
public class UaaMain {
public static void main(String[] args) {
SpringApplication.run(UaaMain.class, args);
}
}
使用@MapperScan注解后会扫描 com.study.*.dao 和 com.study.*.mapper 路径下所有mapper文件,这样就不需要再每个mapper接口上加@Mapper注解标识了
在mapper中自定义方法
package com.study.test.dao;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.study.test.entity.SysUser;
import org.apache.ibatis.annotations.Param;
public interface UserMapper extends BaseMapper<SysUser> {
SysUser getByUserId(@Param("id") Long id);
}
DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.study.test.dao.UserMapper">
<resultMap id="base" type="com.study.test.entity.SysUser">
<result property="id" column="id"/>
<result property="password" column="password"/>
<result property="username" column="username"/>
<result property="code" column="code" />
<result property="age" column="age" />
<result property="roleId" column="rid" />
resultMap>
<select id="getByUserId" resultMap="base" resultType="com.study.test.entity.SysUser">
select * from user where id = #{id}
select>
mapper>
使用UserMapper 里继承自 BaseMapper 里的方法没有问题
使用UserMapper 里的自定义的 getByUserId 方法时报错Invalid bound statement (not found)
这里看到xml中namespace也映射到了对应的mapper
select语句中的id也映射到了mapper中对应的方法名
查看target中编译打包的文件
发现只有Mapper文件,并没有xml文件
这是因为maven打包时默认路径扫描是在src/main/resources路径下
这里将xml文件放在了src/main/java路径下
需要在pom.xml文件中对maven扫描资源路径做一个配置
<build>
<resources>
<resource>
<directory>src/main/javadirectory>
<filtering>falsefiltering>
<includes>
<include>**/*.xmlinclude>
includes>
resource>
<resource>
<directory>src/main/resourcesdirectory>
<filtering>falsefiltering>
<includes>
<include>**/*include>
includes>
resource>
resources>
build>
重新maven clean再maven install发现xml文件打包进去了
再执行上面UserMapper中的getByUserId方法正常