一、RSTFUL API的设计
二、项目初始化和MyBatisPlus的使用
创建项目所需以来包:
1、Lombok
Lombok 是一种 Java 实用工具,可用来帮助开发人员消除 Java 的冗长,尤其是对于简单的 Java 对象(POJO)。它通过注解实现这一目的。要使用Bean对象,必须还要写一些getter和setter方法,可能还要写一个构造器、equals方法、或者hash方法.这些方法很冗长而且没有技术含量,我们叫它样板式代码.lombok的主要作用是通过一些注解,消除样板式代码
常用的几个注解:
@Data : 注在类上,提供类的get、set、equals、hashCode、canEqual、toString方法
@AllArgsConstructor : 注在类上,提供类的全参构造
@NoArgsConstructor : 注在类上,提供类的无参构造
@Setter : 注在属性上,提供 set 方法
@Getter : 注在属性上,提供 get 方法
@EqualsAndHashCode : 注在类上,提供对应的 equals 和 hashCode 方法
@Log4j/@Slf4j : 注在类上,提供对应的 Logger 对象,变量名为 log
2、使用MyBatis-Plus
Mybatis-Plus官方文档:https://baomidou.com/guide/
①引入依赖
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>Latest Version</version>
</dependency>
②配置文件
#tomcat服务器使用的端口
server.port=80
#Spring JDBC 数据源的配置
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/mypetstore
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.username=root
spring.datasource.password=root
#MyBatis-Plus
logging.level.org.csu.mypetstore.api.persistence = trace
③配置MapperScan注解
@SpringBootApplication
@MapperScan("com.baomidou.mybatisplus.samples.quickstart.mapper") //开启包扫描
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
④开始使用
创建实体对象entity
例:
@Data
@TableName("category") //配置实体类对应的表
public class Category {
@TableId(value = "catid",type = IdType.INPUT) //@TableId:主键的映射
private String categoryId;
private String name;
@TableField(value = "descn") //字段映射
private String description;
}
创建Mapper
@Repository
public interface CategoryMapper extends BaseMapper<Category> {
}
简单测试
@Test
void test(){
// List<Category> categoryList =categoryMapper.selectList(null);
// System.out.println((categoryList));
Category category = categoryMapper.selectById("CATS");
System.out.println(category);
}
三、通用响应设计
格式化快捷键(与QQ热键冲突):Ctrl+Alt+L
①创建响应类
package org.csu.mypetstore.api.common;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.Getter;
import java.io.Serializable;
@Getter
//JSON序列化时 空的数据(null)不被包含
@JsonInclude(JsonInclude.Include.NON_NULL)
public class CommonResponse<T> implements Serializable {
private int status;
private String msg;
private T data;
private CommonResponse(int status) {
this.status = status;
}
private CommonResponse(int status, String msg) {
this.status = status;
this.msg = msg;
}
private CommonResponse(int status, T data) {
this.status = status;
this.data = data;
}
private CommonResponse(int status, String msg, T data) {
this.status = status;
this.msg = msg;
this.data = data;
}
@JsonIgnore //JSon默认将所有非静态方法(构造方法除外)序列化,并返回
public boolean isSuccess(){
return this.status == ResponseCode.SUCCESS.getCode();
}
public static <T> CommonResponse<T> createForSuccess() {
return new CommonResponse<T>(ResponseCode.SUCCESS.getCode());
}
public static <T> CommonResponse<T> createForSuccess(T data) {
return new CommonResponse<T>(ResponseCode.SUCCESS.getCode(), data);
}
public static <T> CommonResponse<T> createForSuccessMessage(String msg) {
return new CommonResponse<T>(ResponseCode.SUCCESS.getCode(), msg);
}
public static <T> CommonResponse<T> createForSuccess(String msg, T data) {
return new CommonResponse<T>(ResponseCode.SUCCESS.getCode(), msg, data);
}
public static <T> CommonResponse<T> createForError(String msg){
return new CommonResponse<T>(ResponseCode.ERROR.getCode(),msg);
}
public static <T> CommonResponse<T> createForError(int code,String msg){
return new CommonResponse<T>(code,msg);
}
}
②创建响应信息枚举
package org.csu.mypetstore.api.common;
import lombok.Getter;
//枚举
@Getter
public enum ResponseCode {
SUCCESS(0,"SUCCESS"),
ERROR(1,"ERROR"),
NEED_LOGIN(10,"NEED_LOGIN"),
ILLEGAL_ARGUMENT(2,"ILLEGAL_ARGUMENT");
private final int code;
private final String description;
ResponseCode(int code,String description){
this.code = code;
this.description = description;
}
}
四、第一个接口的实现
创建serivce层
1)定义接口
package org.csu.mypetstore.api.service;
import org.csu.mypetstore.api.common.CommonResponse;
import org.csu.mypetstore.api.entity.Category;
import java.util.List;
public interface CatalogService {
CommonResponse<List<Category>> getCategoryList();
CommonResponse<Category> getCategory(String categoryId);
}
2)实现接口
package org.csu.mypetstore.api.service.impl;
import org.csu.mypetstore.api.common.CommonResponse;
import org.csu.mypetstore.api.entity.Category;
import org.csu.mypetstore.api.persistence.CategoryMapper;
import org.csu.mypetstore.api.service.CatalogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.xml.catalog.Catalog;
import java.util.List;
@Service("catalogService")
public class CatalogServiceImpl implements CatalogService {
@Autowired
CategoryMapper categoryMapper;
@Override
public CommonResponse<List<Category>> getCategoryList() {
List<Category> categoryList = categoryMapper.selectList(null);
if(categoryList.isEmpty()){
return CommonResponse.createForSuccessMessage("没有分类信息");
}
return CommonResponse.createForSuccess(categoryList);
}
@Override
public CommonResponse<Category> getCategory(String categoryId) {
Category category = categoryMapper.selectById(categoryId);
if(category ==null){
return CommonResponse.createForSuccessMessage("没有该ID的Category");
}
return CommonResponse.createForSuccess(category);
}
}
创建Cotroller层进行调用
package org.csu.mypetstore.api.controller.front;
import java.util.*;
import org.csu.mypetstore.api.common.CommonResponse;
import org.csu.mypetstore.api.entity.Category;
import org.csu.mypetstore.api.service.CatalogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
@RequestMapping("/catalog/")
public class CatalogController {
@Autowired
private CatalogService catalogService;
@GetMapping("categories")
@ResponseBody //后台调用fastjson插件
public CommonResponse<List<Category>> getCategoryList(){
return catalogService.getCategoryList();
}
@GetMapping("categories/{id}")
@ResponseBody
public CommonResponse<Category> getCategory(
@PathVariable("id") String categoryId){
return catalogService.getCategory(categoryId);
}
}
五、Item接口的使用和VO的使用
Mybatis-Plus不推荐实用连接查询,因此我们需要使用VO代替这部分功能。
①创建VO所需要的实体类
本例中所需要的实体类为Product、Item、ItemInventory,均包含VO类ItemVO的部分信息
②创建VO类
本例中的VO类为 ItemVO
@Data
public class ItemVO {
//item表中的字段
private int supplierId;
private String itemId;
private String productId;
private BigDecimal listPrice;
private BigDecimal unitCost;
private String status;
private String attribute1;
private String attribute2;
private String attribute3;
private String attribute4;
private String attribute5;
//item所属product的属性
private String categoryId;
private String name;
private String description;
//item的库存,来自inventory表
private int quantity;
}
③在Service层中创建使用到VO对象的接口
CommonResponse<List<ItemVO>> getItemsByProductId( String productId);
④实现创建好的接口
这里展示了如何从不同的实体类中提取信息整合到VO类中并返回
@Override
public CommonResponse<List<ItemVO>> getItemsByProductId(String productId) {
QueryWrapper<Item> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("productId",productId);
//通过productId获取对应的所有items
List<Item> itemList = itemMapper.selectList(queryWrapper);
if(itemList.isEmpty()){
return CommonResponse.createForSuccessMessage("该product下没有item商品");
}
//通过productId获取对应的product
Product product = productMapper.selectById(productId);
//创建需要返回的VOList对象
List<ItemVO> itemVOList = new ArrayList<>();
//将来自不同实体类中的信息整合到VOList对象中
for(Item item:itemList){
ItemVO itemVO = itemToItemVO(item,product);
itemVOList.add(itemVO);
}
//将获取的VOList对象返回
return CommonResponse.createForSuccess(itemVOList);
}
private ItemVO itemToItemVO(Item item,Product product){
ItemVO itemVO = new ItemVO();
itemVO.setItemId(item.getItemId());
itemVO.setProductId(item.getProductId());
itemVO.setListPrice(item.getListPrice());
itemVO.setUnitCost(item.getUnitCost());
itemVO.setStatus(item.getStatus());
itemVO.setAttribute1(item.getAttribute1());
itemVO.setAttribute2(item.getAttribute2());
itemVO.setAttribute3(item.getAttribute1());
itemVO.setAttribute4(item.getAttribute2());
itemVO.setAttribute5(item.getAttribute3());
itemVO.setCategoryId(product.getCategoryId());
itemVO.setName(product.getName());
itemVO.setDescription(product.getDescription());
ItemInventory itemInventory = itemInventoryMapper.selectById(item.getItemId());
itemVO.setQuantity(itemInventory.getQuantity());
return itemVO;
}