Spring Boot MyBatis Plus 查询学生信息 (ID 为 12) - 示例代码
Spring Boot MyBatis Plus 查询学生信息 (ID 为 12) - 示例代码
本文提供一个 Spring Boot 项目中使用 MyBatis Plus 查询学生信息的示例,并详细解释代码实现过程和常见错误解决方法。
代码实现
1. StudentService 接口:
public interface StudentService extends IService<Student> {
}
2. 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);
}
}
3. StudentMapper 接口:
@Mapper
public interface StudentMapper extends BaseMapper<Student> {
}
4. StudentController 控制层:
@Controller
public class StudentController {
@Autowired
private StudentService studentService;
@GetMapping("/student/{id}")
@ResponseBody
public Student getStudentById(@PathVariable("id") Long id) {
return studentService.getById(id);
}
}
5. 查询 ID 为 12 的学生信息:
// 查询id为12的student
Student student = studentService.getById(12L);
错误解决
你遇到的错误信息 org.apache.ibatis.binding.BindingException: Invalid bound statement (not found): com.example.demo1.mapper.StudentMapper.selectById 表示 MyBatis 无法找到 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 接口的包名一致。
总结
本文提供了一个 Spring Boot 项目中使用 MyBatis Plus 查询学生信息的完整示例,并解释了可能遇到的错误以及解决方法。希望对你有所帮助。
注意:
- 确保你的 MyBatis Plus 和 Spring Boot 相关依赖已经正确引入并版本兼容。
- 可以根据你的实际情况修改代码中的类名、方法名和属性名。
原文地址: https://www.cveoy.top/t/topic/lB8q 著作权归作者所有。请勿转载和采集!