SpringBoot 使用 Mybatis Plus 查询 Student 数据

本文将演示如何使用 Mybatis Plus 在 SpringBoot 项目中查询 Student 数据。

1. 项目结构

└── src
    └── main
        └── java
            └── com
                └── example
                    └── demo1
                        └── service
                            └── StudentService.java

2. 代码实现

2.1 StudentService 接口

public interface StudentService extends IService<Student> {

}

2.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);
    }
}

2.3 StudentMapper 接口

@Mapper
public interface StudentMapper extends BaseMapper<Student> {

}

2.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);
    }
}

2.5 查询 id 为 12 的 Student

// 查询id为12的student
Student student = studentService.getById(12L);

3. 错误解决

报错提示为:Invalid bound statement (not found): com.example.demo1.mapper.StudentMapper.selectById,即没有找到 com.example.demo1.mapper.StudentMapper.selectById 这个语句。

原因:

可能是因为在 StudentMapper 接口中没有定义 selectById 方法,或者定义了但是没有在 mapper.xml 中实现对应的 SQL 语句。

解决方法:

  1. 检查 StudentMapper 接口中是否定义了 selectById 方法,如果没有,则添加以下代码:
@Select("SELECT * FROM student WHERE id=#{id}")
Student selectById(Long id);
  1. 检查 mapper.xml 文件中是否有对应的 SQL 语句,如果没有,则添加以下代码:
<select id="selectById" parameterType="long" resultType="com.example.demo1.entity.Student">
    SELECT * FROM student WHERE id = #{id}
</select>

4. 总结

本文演示了如何使用 Mybatis Plus 在 SpringBoot 项目中查询 Student 数据,包括服务层调用、控制层调用等。在实际应用中,可以根据具体需求调整代码实现。

注意:

  • 以上代码仅供参考,实际项目中需要根据具体情况进行调整。
  • 请确保已配置 Mybatis Plus 并引入相关依赖。
  • 请确保 Student 实体类和数据库表结构一致。
  • 如果遇到问题,请检查代码和配置,并参考 Mybatis Plus 官方文档解决。
SpringBoot 使用 Mybatis Plus 查询 Student 数据

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

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