Spring Boot Mybatis Plus 查询学生信息接口实现
public interface StudentService extends IService<Student> {
}
@Service
public class StudentServiceImpl extends ServiceImpl<StudentMapper, Student>
implements StudentService {
@Autowired
private StudentMapper studentMapper;
@Override
public Student getById(Serializable id) {
return studentMapper.selectById(id);
}
}
@Mapper
public interface StudentMapper extends BaseMapper<Student> {
}
@Controller
public class StudentController {
@Autowired
private StudentService studentService;
@GetMapping("/student/{id}")
@ResponseBody
public Student getStudentById(@PathVariable("id") Long id) {
return studentService.getById(id);
}
}
// 查询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接口的全限定名不一致。- 数据库中不存在
id为 12 的记录。
解决方案:
- 在
mapper.xml中添加selectById语句,并确保语句的命名空间与Mapper接口的全限定名一致。 - 检查数据库中是否存在
id为 12 的记录,如果没有则插入一条记录。
示例:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.example.demo1.mapper.StudentMapper">
<select id="selectById" resultType="com.example.demo1.entity.Student">
select * from student where id = #{id}
</select>
</mapper>
注意:
selectById语句的namespace必须与StudentMapper接口的全限定名一致。selectById语句的id属性必须与StudentMapper接口中定义的selectById方法名一致。selectById语句的resultType属性必须与Student实体类的类型一致。
代码示例:
@Mapper
public interface StudentMapper extends BaseMapper<Student> {
// 自定义方法
Student selectById(Long id);
}
原文地址: https://www.cveoy.top/t/topic/lB8w 著作权归作者所有。请勿转载和采集!