Spring Boot Mybatis Plus 学生管理系统:查询学生信息
Spring Boot Mybatis Plus 学生管理系统:查询学生信息
本文将演示如何使用 Spring Boot、Mybatis Plus 和 Spring Data JPA 创建一个简单的学生管理系统,并实现查询学生信息的功能。
1. 项目搭建
首先,创建一个新的 Spring Boot 项目,并添加以下依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.5.2</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
2. 实体类
创建一个名为 Student 的实体类,用于表示学生信息:
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class Student {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private int age;
// 省略getter和setter方法
}
3. 服务层接口
创建一个名为 StudentService 的服务层接口,定义查询学生信息的方法:
import com.baomidou.mybatisplus.extension.service.IService;
public interface StudentService extends IService<Student> {
}
4. 服务层实现类
创建一个名为 StudentServiceImpl 的服务层实现类,实现 StudentService 接口,并使用 Mybatis Plus 提供的 ServiceImpl 类简化代码:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class StudentServiceImpl extends ServiceImpl<StudentMapper, Student>
implements StudentService {
@Autowired
private StudentMapper studentMapper;
@Override
public Student getById(Serializable id) {
return studentMapper.selectById(id);
}
}
5. 数据访问层接口
创建一个名为 StudentMapper 的数据访问层接口,继承 Mybatis Plus 提供的 BaseMapper 接口,并添加查询学生信息的方法:
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface StudentMapper extends BaseMapper<Student> {
}
6. 控制层
创建一个名为 StudentController 的控制层,负责接收请求并调用服务层方法查询学生信息:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class StudentController {
@Autowired
private StudentService studentService;
@GetMapping("/students/{id}")
public ResponseEntity<Student> getStudentById(@PathVariable Long id) {
Student student = studentService.getById(id);
if (student == null) {
return ResponseEntity.notFound().build();
}
return ResponseEntity.ok(student);
}
}
7. 测试
启动项目,使用浏览器访问 http://localhost:8080/students/12,即可查询 id 为 12 的学生信息。
总结
本文演示了如何使用 Spring Boot、Mybatis Plus 和 Spring Data JPA 创建一个简单的学生管理系统,并实现查询学生信息的功能。Mybatis Plus 简化了数据访问层的代码,Spring Data JPA 提供了更便捷的数据库操作方式,使开发效率更高。
代码补充
// 查询id为12的student
Student student = studentService.getById(12);
注意:
- 以上代码仅供参考,实际应用中需要根据具体需求进行调整。
- Mybatis Plus 版本号和依赖库版本号请根据实际情况选择。
- 为了方便阅读,代码中已将双引号改为单引号。
原文地址: https://www.cveoy.top/t/topic/lB8i 著作权归作者所有。请勿转载和采集!