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

可能原因:

  1. mapper.xml 文件中没有定义 selectById 语句。
  2. mapper.xml 文件中定义了 selectById,但是没有正确引入。
  3. mapper.xml 文件中定义了 selectById,但是它的 namespacemapper 接口的包名不一致。

解决方法:

  1. 确认 mapper.xml 文件中是否定义了 selectById 语句。
  2. 确认 mapper.xml 文件中是否正确引入了对应的 mapper 接口。
  3. 确认 mapper.xml 文件中定义的 selectByIdnamespace 是否和 mapper 接口的包名一致。

重要提示: 如果使用注解方式,请确保 @Mapper 注解已正确添加到 mapper 接口上,且 @Service 注解已正确添加到 service 实现类上。

总结

本文提供了一个 Spring Boot MyBatis Plus 查询学生信息的基本示例,并对常见的错误信息进行了分析和解决。希望能够帮助你快速上手 MyBatis Plus 并解决实际开发中的问题。

Spring Boot MyBatis Plus 查询学生信息:完整代码示例和错误排查

原文地址: https://www.cveoy.top/t/topic/lB8r 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录