MyBatis 查询学生信息示例
以下是使用 MyBatis 查询 id 为 12 的学生信息示例代码:
实体类:
public class Student {
private Integer id;
private String name;
private String no;
private String gender;
private Integer classId;
// Getter 和 Setter 方法
}
MyBatis 映射器:
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE mapper
PUBLIC '-//mybatis.org//DTD Mapper 3.0//EN'
'http://mybatis.org/dtd/mybatis-3-mapper.dtd'>
<mapper namespace='com.example.demo1.mapper.StudentMapper'>
<resultMap id='BaseResultMap' type='com.example.demo1.domain.Student'>
<id property='id' column='id' jdbcType='INTEGER'/>
<result property='name' column='name' jdbcType='VARCHAR'/>
<result property='no' column='no' jdbcType='VARCHAR'/>
<result property='gender' column='gender' jdbcType='VARCHAR'/>
<result property='classId' column='class_id' jdbcType='INTEGER'/>
</resultMap>
<sql id='Base_Column_List'>
id,name,no,
gender,class_id
</sql>
</mapper>
服务层代码:
@Service
public class StudentServiceImpl extends ServiceImpl<StudentMapper, Student>
implements StudentService {
@Autowired
private StudentMapper studentMapper;
@Override
public Student getById(Serializable id) {
return studentMapper.selectById(id);
}
}
控制层代码:
@RestController
@RequestMapping('/students')
public class StudentController {
@Autowired
private StudentService studentService;
@GetMapping('/{id}')
public ResponseEntity<Student> getStudentById(@PathVariable Integer id) {
Student student = studentService.getById(id);
return ResponseEntity.ok().body(student);
}
}
说明:
- 实体类
Student中需要包含对应数据库表的字段,以及相应的 getter 和 setter 方法。 - MyBatis 映射器文件
StudentMapper.xml中配置了resultMap和sql语句,用于映射结果集和定义 SQL 语句。 - 服务层接口
StudentService定义了getById方法,用于获取指定 id 的学生信息。 - 服务层实现类
StudentServiceImpl中实现了getById方法,并使用studentMapper.selectById方法从数据库中查询学生信息。 - 控制层
StudentController中定义了一个/students/{id}路径的 GET 请求,用于获取指定 id 的学生信息。
使用示例:
访问 http://localhost:8080/students/12 即可获取 id 为 12 的学生信息。
注意:
- 以上代码示例仅供参考,具体实现需要根据实际情况进行调整。
- 确保配置了 MyBatis 和 Spring Boot,并正确配置了数据库连接信息。
原文地址: https://www.cveoy.top/t/topic/lB8K 著作权归作者所有。请勿转载和采集!