Spring Boot 整合 MyBatis Plus 查询学生信息

本文将使用 Spring Boot 整合 MyBatis Plus 实现学生信息查询功能,包括控制层调用服务层、服务层调用 MyBatis Plus 代码、以及查询 id 为 12 的学生信息。

代码示例

1. 实体类 Student

public class Student {
    private Long id;
    private String name;
    // ...其他属性
}

2. Service 接口 StudentService

public interface StudentService extends IService<Student> {

}

3. Service 实现类 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 student = studentService.getById(12L);

问题分析及解决方案

报错提示为:Invalid bound statement (not found): com.example.demo1.mapper.StudentMapper.selectById,即没有找到 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 接口的包名一致。

如果你使用的是注解方式,那么可能是因为注解的配置有误。请确保以下几点:

  1. @Mapper 注解是否正确添加在 Mapper 接口上。
  2. Mapper 接口是否被 Spring 扫描到了。
  3. 在 MybatisConfig 配置类中是否正确开启了 Mapper 扫描。

如果以上都没有问题,可以尝试使用 @Select 注解来代替 Mapper.xml 中的 select 语句,以避免出现语句未找到的问题。

总结

本文介绍了使用 Spring Boot 整合 MyBatis Plus 实现学生信息查询功能的步骤,并针对常见的错误进行了分析和解决。希望对你有所帮助。

Spring Boot 整合 MyBatis Plus 查询学生信息

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

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