简而言之:
具体步骤如下:
一、创建项目1、创建新模块,并勾选web与sql技术集:
2、手动导入所需的额外依赖:
com.baomidou mybatis-plus-boot-starter3.5.1 com.alibaba druid-spring-boot-starter1.2.6 org.projectlombok lombok
3、修改配置文件:
server:
port: 80
spring:
datasource:
druid:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/test?rewriteBatchedStatements=true
username: root
password: mypassword
mybatis-plus:
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
4、表:
5、构建实体类:
@Data
@NoArgsConstructor
@AllArgsConstructor
@TableName("boot_book")
public class Book extends Model {
@TableId(type = IdType.AUTO)
private Integer id;
private String type;
private String name;
private String description;
}
二、数据层开发
1、构建mapper接口:
@Mapper public interface BookMapper extends BaseMapper{ }
2、配置文件中开启日志,并设置为标准输出:
mybatis-plus:
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
3、配置MP分页插件:
由于没有applicationContext.xml,配置方法与传统MP不同
package com.kvno.config;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class MPConfig {
//分页插件
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor(){
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(new PaginationInnerInterceptor());
return interceptor;
}
}
4、编写测试类:
@SpringBootTest
public class MapperTestCase {
@Autowired
BookMapper bookMapper;
@Test
public void testGetById() {
System.out.println(bookMapper.selectById(1));
}
@Test
public void testInsert() {
Book book = new Book();
book.setName("海绵宝宝");
book.setType("CH");
book.setDescription("yellow");
boolean result = book.insert();
System.out.println(result);
}
@Test
public void testUpdate() {
Book book = new Book();
book.setId(3);
book.setName("海绵宝宝");
book.setType("CH");
book.setDescription("square");
boolean result = book.updateById();
System.out.println(result);
}
@Test
public void testGetAll() {
List books = bookMapper.selectList(null);
for (Book book: books) {
System.out.println(book);
}
}
@Test
public void testGetPage() {
IPage page = new Page<>(1,1);
bookMapper.selectPage(page,null);
System.out.println(page.getCurrent());
System.out.println(page.getSize());
System.out.println(page.getTotal());
System.out.println(page.getPages());
System.out.println(page.getRecords());
}
@Test
public void testWrapper() {
QueryWrapper userQueryWrapper = new QueryWrapper<>();
userQueryWrapper.eq("type","CH");
bookMapper.selectList(userQueryWrapper);
}
}
三、业务层开发
1、定义接口并编写实现类:
public interface BookService {
Boolean insert(Book book);
Boolean update(Book book);
Boolean delete(Integer id);
Book getById(Integer id);
List getAll();
IPage getPage(Integer currentpage,Integer sizePage);
}
@Service
public class BookServiceImpl implements BookService {
@Autowired
private BookMapper bookMapper;
@Override
public Boolean insert(Book book) {
return book.insert();
}
@Override
public Boolean update(Book book) {
return book.updateById();
}
@Override
public Boolean delete(Integer id) {
return bookMapper.deleteById(id) > 0;
}
@Override
public Book getById(Integer id) {
return bookMapper.selectById(id);
}
@Override
public List getAll() {
return bookMapper.selectList(null);
}
@Override
public IPage getPage(Integer currentpage, Integer sizePage) {
IPage page = new Page(currentpage,sizePage);
return bookMapper.selectPage(page,null);
}
}
2、编写测试类:
@SpringBootTest
public class ServiceTestCase {
@Autowired
private BookService bookService;
@Test
void testGetById() {
System.out.println(bookService.getById(1));
}
@Test
public void testInsert() {
Book book = new Book();
book.setName("test");
book.setType("CH");
book.setDescription("service");
bookService.insert(book);
}
@Test
void testUpdate(){
Book book = new Book();
book.setId(4);
book.setDescription("测试数据service");
bookService.update(book);
}
@Test
void testDelete(){
bookService.delete(4);
}
@Test
void testGetAll(){
bookService.getAll();
}
@Test
public void testGetPage() {
IPage page = bookService.getPage(2,1);
System.out.println(page.getCurrent());
System.out.println(page.getSize());
System.out.println(page.getTotal());
System.out.println(page.getPages());
System.out.println(page.getRecords());
}
}
快速开发方案
-
使用MyBatisPlus提供有业务层通用接口(ISerivce
)快速开发service接口,使用业务层通用实现类(ServiceImpl )快速开发service实现类; -
在通用类基础上做功能重载或功能追加;
-
可以编写额外方法,注意重载时不要覆盖原始操作,避免原始提供的功能丢失。
与MP提供的BaseMapper类似,封装了各种业务层方法。简化了开发过程。
1、接口与实现类:
public interface IBookService extends IService{ boolean saveBook(Book book); }
@Service public class QuickBookServiceImp extends ServiceImplimplements IBookService { @Autowired private BookMapper bookMapper; @Override public boolean saveBook(Book book) { return bookMapper.insert(book) > 0; } }
2、测试:
@SpringBootTest
public class QuickServiceTestCase {
@Autowired
private IBookService bookService;
@Test
void testGetById() {
System.out.println(bookService.getById(1));
}
@Test
public void testSave() {
Book book = new Book();
book.setName("test");
book.setType("CH");
book.setDescription("service");
bookService.save(book);
}
@Test
void testUpdate(){
Book book = new Book();
book.setId(4);
book.setDescription("测试数据service");
bookService.updateById(book);
}
@Test
void testDelete(){
bookService.removeById(4);
}
@Test
void testGetAll(){
bookService.list();
}
@Test
public void testGetPage() {
IPage page = new Page(2,1);
bookService.page(page);
System.out.println(page.getCurrent());
System.out.println(page.getSize());
System.out.println(page.getTotal());
System.out.println(page.getPages());
System.out.println(page.getRecords());
}
}
四、表现层开发
- 基于Restful进行表现层接口开发
- 使用Postman测试接口功能
1、编写controller:
注:@RequestBody:接收前端传递给后端的请求体中的数据。
//@RestController
@RequestMapping("/books")
public class BookControllerTest {
@Autowired
private IBookService bookService;
@GetMapping
public List getAll() {
return bookService.list();
}
@PostMapping
public Boolean save(@RequestBody Book book) { //@RequestBody
return bookService.save(book);
}
@PutMapping
public Boolean update(@RequestBody Book book) {
return bookService.updateById(book);
}
@DeleteMapping("/{id}")
public Boolean delete(@PathVariable(value = "id") Integer id) {
return bookService.removeById(id);
}
@GetMapping("/{id}")
public Book getById(@PathVariable(value = "id") Integer id) {
return bookService.getById(id);
}
@GetMapping("/{currentPage}/{pageSize}")
public IPage getPage(@PathVariable int currentPage, @PathVariable int pageSize){
IPage page = new Page(currentPage,pageSize);
return bookService.page(page);
}
}
2、测试:
表现层消息一致性处理返回数据类型不一致会给前端带来不便:
单纯地封装数据又会造成误解,如数据为null时:
故采用以下格式:
优点:
示例:
1、设计表现层返回结果的模型类,用于后端与前端进行数据格式统一,也称为前后端数据协议:
@Data
@NoArgsConstructor
@AllArgsConstructor
public class R { //Result
private Boolean flag;
private Object data;
public R(Boolean flag) {
this.flag = flag;
}
}
2、编写controller:
@RestController
@RequestMapping("/books")
public class BookController {
@Autowired
private IBookService bookService;
@GetMapping
public R getAll() {
return new R(true,bookService.list());
}
@PostMapping
public R save(@RequestBody Book book) { //@RequestBody:接收前端传递给后端的请求体中的数据
return new R(bookService.save(book));
}
@PutMapping
public R update(@RequestBody Book book) {
return new R(bookService.updateById(book));
}
@DeleteMapping("/{id}")
public R delete(@PathVariable(value = "id") Integer id) {
return new R(bookService.removeById(id));
}
@GetMapping("/{id}")
public R getById(@PathVariable(value = "id") Integer id) {
return new R(true,bookService.getById(id));
}
@GetMapping("/{currentPage}/{pageSize}")
public R getPage(@PathVariable int currentPage, @PathVariable int pageSize){
return new R(true,bookService.page(new Page(currentPage,pageSize)));
}
}
3、测试:
异常消息一致性处理
1、使用注解@RestControllerAdvice定义SpringMVC异常处理器,异常处理器必须被扫描加载,否则无法生效;对异常消息进行统一处理,出现异常后返回指定类型:
@RestControllerAdvice
public class ProjectExceptionAdvice {
//拦截所有的异常信息
@ExceptionHandler(Exception.class)
public R doException(Exception ex){
//记录日志
//通知运维
//通知开发
ex.printStackTrace(); //控制台仍然要显示异常
return new R(false,"服务器故障,请稍后再试!");
}
}
2、修改表现层返回结果的模型类,封装出现异常后对应的信息:
@Data
@NoArgsConstructor
@AllArgsConstructor
public class R { //Result
private Boolean flag;
private Object data;
private String msg;
public R(Boolean flag) {
this.flag = flag;
}
public R(Boolean flag,Object data) {
this.flag = flag;
this.data = data;
}
public R(Boolean flag,String msg) {
this.flag = flag;
this.msg = msg;
}
}



