MyBatis Plus 是一个 MyBatis 的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生。以下是一个使用 MyBatis Plus 实现的 Student
表的标准 CRUD 操作的示例代码。
首先,你需要定义一个实体类 Student
,对应数据库中的 student
表:
public class Student {
private Long id;
private String name;
private Integer age;
// 省略其他字段、getter 和 setter 方法
}
然后,创建一个 Mapper 接口,继承 BaseMapper<Student>
:
public interface StudentMapper extends BaseMapper<Student> {
// 在这里可以添加自定义的方法
}
接下来,创建 Service 接口和实现类:
public interface IStudentService {
// 定义业务方法
void saveStudent(Student student);
Student getById(Long id);
List<Student> listStudents();
void updateStudent(Student student);
void removeStudent(Long id);
}
@Service
public class StudentService implements IStudentService {
@Autowired
private StudentMapper studentMapper;
@Override
public void saveStudent(Student student) {
studentMapper.insert(student);
}
@Override
public Student getById(Long id) {
return studentMapper.selectById(id);
}
@Override
public List<Student> listStudents() {
return studentMapper.selectList(null);
}
@Override
public void updateStudent(Student student) {
studentMapper.updateById(student);
}
@Override
public void removeStudent(Long id) {
studentMapper.deleteById(id);
}
}
最后,你可以在控制器中调用 Service 层的方法:
@RestController
@RequestMapping("/student")
public class StudentController {
@Autowired
private IStudentService studentService;
@PostMapping("/save")
public ResponseEntity<?> saveStudent(@RequestBody Student student) {
studentService.saveStudent(student);
return ResponseEntity.ok().build();
}
@GetMapping("/get/{id}")
public ResponseEntity<?> getById(@PathVariable Long id) {
Student student = studentService.getById(id);
return ResponseEntity.ok(student);
}
@GetMapping("/list")
public ResponseEntity<List<Student>> listStudents() {
List<Student> students = studentService.listStudents();
return ResponseEntity.ok(students);
}
@PutMapping("/update")
public ResponseEntity<?> updateStudent(@RequestBody Student student) {
studentService.updateStudent(student);
return ResponseEntity.ok().build();
}
@DeleteMapping("/remove/{id}")
public ResponseEntity<?> removeStudent(@PathVariable Long id) {
studentService.removeStudent(id);
return ResponseEntity.ok().build();
}
}
以上代码提供了一个基本的 CRUD 操作示例,包括:
saveStudent
:保存学生信息。getById
:根据 ID 获取学生信息。listStudents
:列出所有学生。updateStudent
:更新学生信息。removeStudent
:根据 ID 删除学生信息。
请注意,这只是一个示例,实际使用时你可能需要添加更多的业务逻辑和异常处理。此外,你可能还需要配置 MyBatis Plus 的相关配置文件和数据库连接信息。