Spring Boot MyBatis Plus 查询学生信息:完整代码示例和错误排查
Spring Boot MyBatis Plus 查询学生信息:完整代码示例和错误排查
本示例演示使用 Spring Boot 和 MyBatis Plus 实现学生信息的查询操作,包括控制器层、服务层和数据访问层。
1. 实体类
public class Student {
private Long id;
private String name;
private Integer age;
// getter and setter
}
2. 服务接口
public interface StudentService extends IService<Student> {
}
3. 服务实现类
@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
public interface StudentMapper extends BaseMapper<Student> {
}
5. 控制器层
@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);
错误排查
错误信息: org.apache.ibatis.binding.BindingException: Invalid bound statement (not found): 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 接口上,且 @Service 注解已正确添加到 service 实现类上。
总结
本文提供了一个 Spring Boot MyBatis Plus 查询学生信息的基本示例,并对常见的错误信息进行了分析和解决。希望能够帮助你快速上手 MyBatis Plus 并解决实际开发中的问题。
原文地址: https://www.cveoy.top/t/topic/lB8r 著作权归作者所有。请勿转载和采集!