使用 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 实体类的基本方法,可以根据实际需求进行调整和扩展

MyBatis 查询 Student 实体类示例:根据 ID 获取学生信息

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

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