1. 创建Spring Boot项目
如果start.spring.io
连接失败, 可以尝试改成start.springboot.io
2.maven引入一下常见包
如果idea没有自动识别为maven项目, 右键'pom.xml'->'Add as Maven Project'
mybatis-plus和gson
<!-- https://mvnrepository.com/artifact/com.baomidou/mybatis-plus-boot-starter -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.google.code.gson/gson -->
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.9</version>
</dependency>
3.建立实体类和分层页面
com.example.back
-pojo.Student
-mapper.StudentMapper
-controller.StudentController
在启动类BackApplication
中, 添加@MapperScan("com.example.back.mapper")
注解.
①.Student实体类
@Data // Lombok注解
public class Student {
private Long id;
private String name;
private Integer age;
private Integer chi;
private Integer math;
private Integer english;
}
②. mapper映射类
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
public interface StudentMapper extends BaseMapper<Student> {
}
③. 书写controller接口
@Autowired
private StudentMapper mapper;
private Gson gson = new Gson();
@GetMapping("/getAll")
public String getAll() {
return gson.toJson(mapper.selectList(null)) ;
}
@PostMapping("/update")
public void update(@RequestBody Student student){
mapper.updateById(student);
}
@PostMapping("/insert")
public void insert(@RequestBody Student student) {
mapper.insert(student);
}
@PostMapping("/delete")
public void delete(@RequestBody Student student){
mapper.deleteById(student.getId());
}