MyBatis 查询 Student 实体类示例:根据 ID 获取学生信息
使用 MyBatis 查询 Student 实体类示例
场景: 根据 ID 查询一个 Student 实体类。
代码示例:
**1. 实体类(Student.java):**javapublic class Student { private Integer id; private String name; private String no; private String gender; private Integer classId;
// 省略getter和setter方法}
**2. Mapper 接口 (StudentMapper.java):**java@Mapperpublic interface StudentMapper extends BaseMapper
}
**3. 服务层接口 (StudentService.java):**javapublic interface StudentService extends IService
}
**4. 服务层实现 (StudentServiceImpl.java):**java@Servicepublic class StudentServiceImpl extends ServiceImpl<StudentMapper, Student> implements StudentService {
// 不需要重写getById方法,直接调用父类的方法即可
}
**5. 控制层 (StudentController.java):**java@Controller@RequestMapping('/student')public class StudentController {
@Autowired private StudentService studentService;
@GetMapping('/{id}') public ResponseEntity<Student> getById(@PathVariable('id') Integer id) { Student student = studentService.getById(id); if (student == null) { return ResponseEntity.notFound().build(); } return ResponseEntity.ok(student); }}
代码说明:
- 实体类
Student中的属性名要与数据库表中的列名一致,这样才能直接进行映射。*StudentMapper接口继承了BaseMapper接口,并使用@Mapper注解进行标识,以便 MyBatis 可以扫描并生成 Mapper 代理类。*StudentService接口继承了IService接口,并定义了getById方法,用于查询学生信息。*StudentServiceImpl类实现了StudentService接口,并继承了ServiceImpl类,它提供了基本的 CRUD 操作,包括getById方法,不需要额外编写代码。*StudentController类中使用@GetMapping注解定义了getById方法,该方法接受一个id参数,并调用studentService.getById()方法查询学生信息。
注意事项:
- 确保
Student实体类中的属性名与数据库表中的列名一致。* 确保StudentMapper.xml文件存在,并且包含resultMap映射关系,用于指定属性名和数据库列名的对应关系。* 使用@Autowired注解注入StudentService实例,以便在控制层中调用服务层的方法。
总结:
以上示例展示了使用 MyBatis 查询 Student 实体类的基本方法,可以根据实际需求进行调整和扩展
原文地址: https://www.cveoy.top/t/topic/lB8L 著作权归作者所有。请勿转载和采集!