Spring Boot 整合 MyBatis Plus 查询学生信息
Spring Boot 整合 MyBatis Plus 查询学生信息
本文将使用 Spring Boot 整合 MyBatis Plus 实现学生信息查询功能,包括控制层调用服务层、服务层调用 MyBatis Plus 代码、以及查询 id 为 12 的学生信息。
代码示例
1. 实体类 Student
public class Student {
private Long id;
private String name;
// ...其他属性
}
2. Service 接口 StudentService
public interface StudentService extends IService<Student> {
}
3. Service 实现类 StudentServiceImpl
@Service
public class StudentServiceImpl extends ServiceImpl<StudentMapper, Student>
implements StudentService {
@Autowired
private StudentMapper studentMapper;
@Override
public Student getById(Serializable id) {
return studentMapper.selectById(id);
}
}
4. Mapper 接口 StudentMapper
@Mapper
public interface StudentMapper extends BaseMapper<Student> {
}
5. 控制层 StudentController
@Controller
public class StudentController {
@Autowired
private StudentService studentService;
@GetMapping("/student/{id}")
@ResponseBody
public Student getStudentById(@PathVariable("id") Long id) {
return studentService.getById(id);
}
}
6. 测试代码
// 查询id为12的student
Student student = studentService.getById(12L);
问题分析及解决方案
报错提示为:Invalid bound statement (not found): com.example.demo1.mapper.StudentMapper.selectById,即没有找到 com.example.demo1.mapper.StudentMapper.selectById 这个语句。
可能原因:
mapper.xml中没有定义selectById这个语句。mapper.xml中定义了selectById,但是没有正确引入。- 在
mapper.xml中定义了selectById,但是它的namespace和mapper接口的包名不一致。
解决方法:
- 确认
mapper.xml中是否定义了selectById这个语句。 - 确认
mapper.xml中是否正确引入了对应的mapper接口。 - 确认
mapper.xml中定义的selectById的namespace是否和mapper接口的包名一致。
如果你使用的是注解方式,那么可能是因为注解的配置有误。请确保以下几点:
@Mapper注解是否正确添加在Mapper接口上。Mapper接口是否被 Spring 扫描到了。- 在 MybatisConfig 配置类中是否正确开启了
Mapper扫描。
如果以上都没有问题,可以尝试使用 @Select 注解来代替 Mapper.xml 中的 select 语句,以避免出现语句未找到的问题。
总结
本文介绍了使用 Spring Boot 整合 MyBatis Plus 实现学生信息查询功能的步骤,并针对常见的错误进行了分析和解决。希望对你有所帮助。
原文地址: https://www.cveoy.top/t/topic/lB8t 著作权归作者所有。请勿转载和采集!