问题原因:未正确加载相关文件。
@MapperScan注解的作用。
添加@MapperScan(“com.example.example”)注解以后,com.example.example包下面的所有接口类,在编译之后都会生成相应的实现类。
该功能是为了替代@Mapper注解。@Mapper注解在每个Mapper接口上添加,在编译时会为该Mapper接口生成相应的实现类。例如:
@Mapper
public interface UserMapper extends BaseMapper<UserPO> {
}
但是大家觉得为每一个Mapper接口上添加@Mapper注释太繁琐,于是就有了@MapperScan,这样在Application中添加 @MapperScan后,不用再为Mapper接口添加@Mapper注释。就变成这样:
# MyspbprojectApplication.java
@RestController
@SpringBootApplication
@MapperScan("com.mylove.myspbproject.module.*.repo.*")
public class MyspbprojectApplication {
public static void main(String[] args) {
SpringApplication.run(MyspbprojectApplication.class, args);
System.out.println("app start success");
}
}
# UserMapper.java
@Repository
public interface UserMapper extends BaseMapper<UserPO> {
}
实际问题解决
导致Invalid bound statement (not found)的具体原因:
1. @MapperScan 配置得路径没有包含Mapper接口,导致没有为Mapper接口生成实现类。
解决: 还用说吗,@MapperScan指定的路径包含所有Mapper.java即可。
2. @MapperScan将其它不需要编译器自动实现的接口也包含进去了。这会导致controller中不能直接调用service,却可以正常调用serviceImpl。
解决:将@MapperScan指定的路径精确到Mapper,不要影响到其它接口类即可。
3. 上面的1和2都没有问题,那就是Mapper本身的问题。
解决:
接口名要与mapper文件要一致
mapper.xml的命名规范遵守: 接口名+Mapper.xml
mapper.xml的namespace要写所映射接口的全称类名。
mapper.xml中的每个statement的id要和接口方法的方法名相同
mapper.xml中定义的每个sql的parameterType要和接口方法的形参类型相同
mapper.xml中定义的每个sql的resultType要和接口方法的返回值的类型相同
mapper.xml要和对应的mapper接口在同一个包下(当然你可以在配置文件中显式指定.xml文件的位置)。