mapper类不能被发现
时间: 2023-10-21 08:03:40 浏览: 50
如果在使用 Spring Boot 和 MyBatis 进行开发时,mapper 类无法被发现,可以尝试以下几个方法:
1. 确认 mapper 接口所在的包是否在 `@MapperScan` 注解中被扫描到。`@MapperScan` 注解通常被用于指定 mapper 接口所在的包,让 MyBatis 自动扫描并生成代理类。例如:
```
@MapperScan("com.example.mapper")
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
```
2. 确认 mapper 接口的命名规范是否正确。MyBatis 的 mapper 接口命名规范是在 mapper 接口名后面加上 `Mapper`,并且与对应的 mapper.xml 文件同名,例如:
```
public interface UserMapper {
User selectById(int id);
}
```
对应的 mapper.xml 文件名应该是 `UserMapper.xml`。
3. 确认 mapper.xml 文件是否被正确加载。MyBatis 的 mapper.xml 文件需要被正确加载才能够被使用。可以在 `application.properties` 文件中配置 `mybatis.mapper-locations` 属性,指定 mapper.xml 文件所在的路径。例如:
```
mybatis.mapper-locations=classpath:mapper/*.xml
```
4. 确认 mapper 接口是否被正确注入。可以在 mapper 接口上添加 `@Autowired` 注解,让 Spring 自动注入 mapper 接口的实例。例如:
```
@RestController
public class UserController {
@Autowired
private UserMapper userMapper;
@GetMapping("/user/{id}")
public User getUserById(@PathVariable("id") int id) {
return userMapper.selectById(id);
}
}
```
在上述代码中,`@Autowired` 注解会让 Spring 自动注入 `UserMapper` 的实例,从而可以使用其中定义的方法。