上一章节,我们已经在项目中集成了MyBatis-Plus,创建了student表,并使用代码生成器将其代码生成好了,那么这章节,我们开始介绍MyBatis-Plus的使用。
保存记录
我们对前面章节的"提交学生信息"方法进行调整,让前端提交的信息保存到学生表中。
package org.liurb.springboot.demo.controller;
import org.liurb.springboot.demo.dto.StudentDto;
import org.liurb.springboot.demo.entity.Student;
import org.liurb.springboot.demo.response.Result;
import org.liurb.springboot.demo.response.ResultUtil;
import org.liurb.springboot.demo.service.StudentService;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import javax.validation.Valid;
import java.time.LocalDateTime;
@RestController
@RequestMapping("/springboot/demo")
public class DemoController {
@Resource
StudentService studentService;
/**
* 提交学生信息
*
* @param studentDto
* @return
*/
@PutMapping("/student")
public Result student(@RequestBody @Valid StudentDto studentDto) {
String name = studentDto.getName();
int age = studentDto.getAge();
String sex = studentDto.getSex();
Student student = new Student();
student.setName(name);
student.setAge(age);
student.setSex(sex);
student.setCreatedAt(LocalDateTime.now());
studentService.save(student);
//返回成功
return ResultUtil.success("保存成功");
}
}
首先在控制器中,注入学生表的接口。
然后,我们将前端提交的信息赋值到学生表的实体中。
String name = studentDto.getName();
int age = studentDto.getAge();
String sex = studentDto.getSex();
Student student = new Student();
student.setName(name);
student.setAge(age);
student.setSex(sex);
student.setCreatedAt(LocalDateTime.now());
最后,我们调用学生表接口的save方法,保存学生实体记录。
//save方法是Mybatis-Plus封装的方法,用于保存实体对象
studentService.save(student);
到此,保存学生信息的接口就写完了,我们用postman工具调用一下这个接口。
接口提示我们保存正常,并没有异常。
查看一下demo_student数据表 ,记录插入成功,没有问题。
查询记录
那么如果要查询"学生姓名为张三"的记录,应该怎么实现呢?
根据Restful设计风格,我们再添加一个get方法,用于根据学生名称获取其信息的接口,并返回该学生记录信息。
/**
* 获取学生信息
*
* @param name
* @return
*/
@GetMapping("/student/{name}")
public Result getStudent(@PathVariable String name) {
Student student = studentService.getOne(new LambdaQueryWrapper<Student>().eq(Student::getName, name));
//返回成功
return ResultUtil.success(student);
}
getOne这个方法的参数是一个Wrapper,我们这边使用的是LambdaQueryWrapper,这个实现接口支持Lambda表达式的写法,对于Lambda表达式的介绍,可以看这个文章 Java Lambda 表达式
使用postman工具,调用一下这个接口。
如上图所示,请求成功,并返回了"张三"同学的信息。