Spring Boot Mybatis Plus 查询学生信息 - 使用注解方式
Spring Boot Mybatis Plus 查询学生信息 - 使用注解方式
本文介绍使用 Spring Boot 和 Mybatis Plus 注解方式实现学生信息查询功能,并解决常见报错问题。
代码示例
1. 实体类 (Student)
public class Student {
private Long id;
private String name;
// 其他属性...
// getter 和 setter 方法
}
2. 接口 (StudentService)
public interface StudentService extends IService<Student> {
}
3. 实现类 (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 = 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 接口中是否正确定义了 selectById 方法,并且方法名和参数与 mapper.xml 中定义的一致。
- 确认在 mapper 接口上是否添加了 @Mapper 注解,以便让 MyBatis 能够正确识别。
- 确认在 Service 实现类中是否正确注入了对应的 mapper 接口,并且实现了 Service 接口中的方法。
- 确认在 Service 实现类中调用 mapper 接口的方法时,是否使用了正确的方法名和参数。
- 确认在 mapper.xml 中是否正确引入了对应的 mapper 接口。
- 确认在 mapper.xml 中定义的 selectById 的 namespace 是否和 mapper 接口上的 @Mapper 注解中的值一致。
- 确认项目中的相关依赖是否正确引入,并且版本是否匹配。
- 尝试重新构建项目,或者清除缓存再运行。
总结
本文介绍了使用 Spring Boot 和 Mybatis Plus 注解方式实现学生信息查询功能,并解决常见报错问题。希望本文能够帮助你更好地理解和使用 Mybatis Plus。
原文地址: https://www.cveoy.top/t/topic/lB8s 著作权归作者所有。请勿转载和采集!