小记
1.时间转换工具类
DateUtils
package com.zj.sellermanager.web.util;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateUtils {
private static final String DEFAULT_FORMAT = "yyyy-MM-dd HH:mm:ss";
public static String getDateStr(Date date){
return new SimpleDateFormat(DEFAULT_FORMAT).format(date);
}
public static String getDateStr(Date date, String format){
return new SimpleDateFormat(format).format(date);
}
public static Date getDate(String dateStr){
try {
return new SimpleDateFormat(DEFAULT_FORMAT).parse(dateStr);
} catch (ParseException e) {
return null;
}
}
public static Date getDate(String dateStr, String format){
try {
return new SimpleDateFormat(format).parse(dateStr);
} catch (ParseException e) {
return null;
}
}
}
2.Swagger文档
SwaggerConfig.java
package com.zj.sellermanager.web.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
/**
* @program: Boot2003
* @description: Swagger测试文档
* @author: xinghe
* @create: 2020-12-17 11:38
*/
@Configuration //标记这是一个配置
@EnableSwagger2 //启用Swagger
public class SwaggerConfig {
private ApiInfo createAI(){
return new ApiInfoBuilder().title("文玩云仓项目用户服务的App接口文档").//设置标题
contact(new Contact("zjkj","http://baidu.com","zjkj@163.com"))
.version("1.0").description("这是一个在线接口文档,可以直接查看接口的信息并且可以实现接口的测试")
.build();
}
//构建Swagger 对象
@Bean //使用Spring IOC创建实例
public Docket createD(){
return new Docket(DocumentationType.SWAGGER_2).//指定生成那种类型的文档
apiInfo(createAI())//文档信息
.select().apis(RequestHandlerSelectors.basePackage("com.zj.sellermanager.web.controller")).//扫描接口所在的包
build();
}
}
3.搜索条件是范围时(时间范围、数字范围)
we 层入参:queryParam
/**
* 创建时间
*/
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private List<String> createTime;
/**
* 付款时间
*/
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private List<String> payTime;
/**
* 完结时间
*/
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private List<String> endTime;
/**
* 订单金额
*/
private Integer money;
dao 层入参 doParam
/**
* 创建时间左区间
*/
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private Date minCreateTime;
/**
* 创建时间右区间
*/
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private Date maxCreateTime;
/**
* 付款时间左区间
*/
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private Date minPayTime;
/**
* 付款时间右区间
*/
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private Date maxPayTime;
/**
* 完结时间左区间
*/
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private Date minEndTime;
/**
* 完结时间右区间
*/
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private Date maxEndTime;
/**
* 订单金额左区间
*/
private Integer minMoney;
/**
* 订单金额右区间
*/
private Integer maxMoney;
SQL语句编写
<if test="minCreateTime != null and maxCreateTime != null">
and DATE_FORMAT(create_time, "%Y-%m-%d %H:%i:%S") BETWEEN DATE_FORMAT(#{minCreateTime}, "%Y-%m-%d %H:%i:%S") AND DATE_FORMAT(#{maxCreateTime}, "%Y-%m-%d %H:%i:%S")
</if>
<if test="minPayTime != null and maxPayTime != null">
and DATE_FORMAT(pay_time, "%Y-%m-%d %H:%i:%S" BETWEEN DATE_FORMAT(#{minPayTime}, "%Y-%m-%d %H:%i:%S") AND DATE_FORMAT(#{maxPayTime}, "%Y-%m-%d %H:%i:%S")
</if>
<if test="minEndTime != null and maxEndTime != null">
and DATE_FORMAT(end_time, "%Y-%m-%d %H:%i:%S") BETWEEN DATE_FORMAT(#{minEndTime}, "%Y-%m-%d %H:%i:%S") AND DATE_FORMAT(#{maxEndTime}, "%Y-%m-%d %H:%i:%S")
</if>
<if test="minMoney != null">
and money >= #{minMoney}
</if>
<if test="maxMoney != null">
and money <= #{maxMoney}
</if>
web层参数转换(queryParam->doParam)
//转换创建时间
try {
List<String> createTime = orderQueryParam.getCreateTime();
if (createTime == null) {
return orderDoParam;
}
if (createTime.get(0) != null) {
orderDoParam.setMinCreateTime(DateUtils.getDate(DateUtils.getDateStr(DateUtils.getDate(createTime.get(0)), "yyyy-MM-dd") + " 00:00:00"));
}
if (createTime.get(1) != null) {
orderDoParam.setMaxCreateTime(DateUtils.getDate(DateUtils.getDateStr(DateUtils.getDate(createTime.get(1)), "yyyy-MM-dd") + " 00:00:00"));
}
} catch (Exception e) {
log.error("convertParam createTime:{}", orderQueryParam, e);
}
//转换付款时间
try {
List<String> payTime = orderQueryParam.getPayTime();
if (payTime == null) {
return orderDoParam;
}
if (payTime.get(0) != null) {
orderDoParam.setMinPayTime(DateUtils.getDate(DateUtils.getDateStr(DateUtils.getDate(payTime.get(0)), "yyyy-MM-dd") + " 00:00:00"));
}
if (payTime.get(1) != null) {
orderDoParam.setMaxPayTime(DateUtils.getDate(DateUtils.getDateStr(DateUtils.getDate(payTime.get(1)), "yyyy-MM-dd") + " 00:00:00"));
}
} catch (Exception e) {
log.error("convertParam payTime:{}", orderQueryParam, e);
}
//转换完结时间
try {
List<String> endTime = orderQueryParam.getEndTime();
if (endTime == null) {
return orderDoParam;
}
if (endTime.get(0) != null) {
orderDoParam.setMinEndTime(DateUtils.getDate(DateUtils.getDateStr(DateUtils.getDate(endTime.get(0)), "yyyy-MM-dd") + " 00:00:00"));
}
if (endTime.get(1) != null) {
orderDoParam.setMaxPayTime(DateUtils.getDate(DateUtils.getDateStr(DateUtils.getDate(endTime.get(1)), "yyyy-MM-dd") + " 00:00:00"));
}
} catch (Exception e) {
log.error("convertParam endTime:{}", orderQueryParam, e);
}
//转换订单金额
try {
Map<String,Object> money = JSONObject.parseObject(JSON.toJSONString(orderQueryParam.getMoney()));
if (money == null) {
return orderDoParam;
}
if (money.get("min") != null) {
orderDoParam.setMinMoney(Integer.parseInt(money.get("min").toString()));
}
if (money.get("max") != null) {
orderDoParam.setMaxMoney(Integer.parseInt(money.get("max").toString()));
}
} catch (Exception e) {
log.error("convertParam money:{}", orderQueryParam, e);
}
controller 层分页按条件查询
@PostMapping("findByPage")
@ApiOperation("findByPage-订单按条件分页查询列表")
public ApiResult<List<OrderVo>> findByPage(OrderQueryParam orderQueryParam) {
if (orderQueryParam == null) {
return new ApiResult(SellerCodeEnum.NO_DATA.getCode(),SellerCodeEnum.NO_DATA.getDesc());
}
OrderDoParam orderDoParam = convertOrderDoParam(orderQueryParam);
orderDoParam.setCurrent((Optional.ofNullable(orderQueryParam.getCurrent()).orElse(1) - 1) * Optional.ofNullable(orderQueryParam.getPageSize()).orElse(20));
PagerResult<Order> pagerResult = orderManagerService.findByPage(orderDoParam);
return new ApiResult(new PagerResult<>(pagerResult.getTotal(),orderQueryParam.getCurrent(),orderQueryParam.getPageSize(), OrderConvertUtils.convertOrderVoList(pagerResult.getData())));
}
4.忽略前端多传的参数
在入参实体类上加上注解
@JsonIgnoreProperties(ignoreUnknown = true)
5.一个搜索框允许多数据查询
用list接收前端传过来的参数
eg:
/**
* 店铺标签数组
*/
private List<Integer> tagIdList;
sql语句编写:
<if test="idList != null and idList.size() > 0">
and id in
<foreach collection="idList" item="item" index="index" open="(" close=")" separator="or">
FIND_IN_SET(#{item}, REPLACE(REPLACE(`id`,'[',''),']',''))
</foreach>
</if>
6.模糊查询
sql语句编写
<if test="shopName != null and shopName != ''">
<bind name="shopName" value="'%' + shopName + '%'"/>
and shop_name like #{shopName}
</if>
7.添加或删除一个字段的部分数据
思路:
用一个字段接收是添加还是删除,然后进行操作
1.把原先对象的字段数据查出来放进list里 (我这里时String->list)
2.将前端传过来的数据(这里前端也会传给我一个list),进行遍历
3.两个list同时遍历比较里面的数据是否相等
4.我在添加时做了过滤操作,避免重复添加数据
5.sql传入对象正常修改即可
controller:
//批量更新店铺标签
@PostMapping("batchModifyShop")
@ApiOperation("batchModifyShop-批量更新店铺")
public ApiResult<Boolean> batchModifyShop(@RequestBody BathUpdateShopVo shopVo) {
//参数合法性判断
if (shopVo.getShopIds() == null) {
return new ApiResult(SellerCodeEnum.PARAM_LACK.getCode(), SellerCodeEnum.PARAM_LACK.getDesc());
}
for (Long id : shopVo.getShopIds()) {
//1.把原先的数据查出来
Shop shop = shopManagerService.queryById(id);
//2.遍历查询原先的数据
List<String> shopList = Arrays.asList(shop.getTagId().split(","));
List<Integer> tagIdList = shopList.stream().map(Integer::parseInt).collect(Collectors.toList());
List<Integer> importTagIds = shopVo.getTagId();
if (shopVo.getTagType() == 0) {
//3.业务逻辑
for (Integer importTagId : importTagIds) {
for (int i = 0; i < tagIdList.size(); i++) {
//执行删除操作
if (tagIdList.get(i).equals(importTagId)) {
tagIdList.remove(i);
}
}
}
//4.执行操作
shop.setTagId(StringUtils.join(tagIdList.toArray(), ","));
shopManagerService.modifyShopTag(shop);
}
//1.添加数据,遍历查询
if (shopVo.getTagType() == 1) {
//业务逻辑
for (Integer importTagId : importTagIds) {
for (int i = 0; i < tagIdList.size(); i++) {
if (!tagIdList.get(i).equals(importTagId)) {
//2.添加
tagIdList.add(importTagId);
}
}
}
//3.执行操作 过滤重复元素
List<Integer> list = tagIdList.stream().distinct().collect(Collectors.toList());
shop.setTagId(StringUtils.join(list.toArray(), ","));
shopManagerService.modifyShopTag(shop);
}
}
return new ApiResult(true);
}
8.将数据库中的Id转成文字到前端显示
出参赋值给另一个字段传到前端显示
转换类
controller层转换类
//转换类
private List<ShopVo> convertShopList(List<Shop> shopList, List<User> userList) {
if (CollectionUtils.isEmpty(shopList)) {
return Collections.EMPTY_LIST;
}
List<ShopVo> shopVoList = Lists.newArrayList();
for (Shop shop : shopList) {
//创建人
Map<Integer, User> userMap = Maps.newHashMap();
if (CollectionUtils.isNotEmpty(userList)) {
userMap = userList.stream().collect(Collectors.toMap(User::getId, Function.identity()));
}
String userName = "";
if (Objects.nonNull(shop.getCreatorId())) {
User user = userMap.get(shop.getCreatorId());
userName = user == null ? "" : user.getUsername();
}
ShopVo shopVo = convertShopVo(shop, userName);
BeanUtils.copyProperties(shop, shopVo);
//标签
if (Objects.nonNull(shop.getTagId())) {
//字符串转list
if (shop.getTagId() != null) {
if (!shop.getTagId().equals("")) {
List<String> shopList1 = Arrays.asList(shop.getTagId().split(","));
//String转Integer
List<Integer> tagList = shopList1.stream().map(Integer::parseInt).collect(Collectors.toList());
if (!CollectionUtils.isEmpty(tagList)) {
List<Tag> tags = tagService.queryByTagIds(tagList);
List<String> tagNameList = tags.stream().map(Tag::getTagName).collect(Collectors.toList());
shopVo.setTagName(tagNameList);
} else {
shopVo.setTagName(Collections.EMPTY_LIST);
}
} else {
shopVo.setTagName(Collections.EMPTY_LIST);
}
shopVoList.add(shopVo);
}
}
}
return shopVoList;
}
convert工具类
public static ShopVo convertShopVo(Shop shop, String userName){
if(shop == null){
return null;
}
ShopVo shopVo = new ShopVo();
BeanUtils.copyProperties(shop,shopVo);
shopVo.setCreatedAt(shop.getCreatedAt() == null ? "" : DateTimeUtil.getStringDate(shop.getCreatedAt()));
shopVo.setUpdatedAt(shop.getUpdatedAt() == null ? "" : DateTimeUtil.getStringDate(shop.getUpdatedAt()));
shopVo.setJwtObtainTime(shop.getJwtObtainTime() == null ? "" : DateTimeUtil.getStringDate(shop.getJwtObtainTime()));
shopVo.setJwtExpireTime(shop.getJwtExpireTime() == null ? "" : DateTimeUtil.getStringDate(shop.getJwtExpireTime()));
shopVo.setCreateName(userName);
return shopVo;
}
9.String<->list相互转换的两种方式
1.带[]
//String转list
List<Integer> labelld = JSON.parseArray(wwdzOperateGoods.getLabelId(), Integer.class);
//list转String
String s = JSON.toJSONString(wwdzOperateGoodsDoParam);
2.不带[]
//String转list
List<String> shopList1 = Arrays.asList(shop.getTagId().split(","));
//String转Integer
List<Integer> tagList = shopList1.stream().map(Integer::parseInt).collect(Collectors.toList());
//list转String
String join = StringUtils.join(tagIdList.toArray(), ",");
10.分页工具类PagerResult
package com.zj.sellermanager.biz.common;
import lombok.Data;
import java.io.Serializable;
import java.util.List;
@Data
public class PagerResult<T> implements Serializable {
private static final long serialVersionUID = 1L;
//("总条数")
private Integer total;
//("当前页数")
private Integer current;
//("每页记录数")
private Integer pageSize;
//("数据列表")
private List<T> data;
public PagerResult(Integer total, Integer current, Integer pageSize, List<T> data) {
this.total = total;
this.current = current;
this.pageSize = pageSize;
this.data = data;
}
public PagerResult(Integer total, List<T> data) {
this.total = total;
this.data = data;
}
}
11.ApiResult工具类
package com.zj.sellermanager.web.vo;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.zj.sellermanager.web.enums.SellerCodeEnum;
import lombok.Data;
import java.io.Serializable;
@Data
public class ApiResult<T> implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 错误码
* 必定返回
*/
private Integer code;
/**
* 错误信息
* 必定返回
*/
private String message;
/**
* 业务数据对象
*/
@JsonInclude(JsonInclude.Include.NON_NULL)
private T data;
/**
* 构造函数
*
* @param code
* @param message
* @param data
*/
public ApiResult(Integer code, String message, T data) {
this.code = code;
this.message = message;
this.data = data;
}
/**
* 开放平台处理失败
*
* @param code
* @param message
*/
public ApiResult(Integer code, String message) {
this(code, message, null);
}
/**
* 给予错误码的构造函数
*
* @param stateCodeEnum
*/
public ApiResult(SellerCodeEnum stateCodeEnum) {
this(stateCodeEnum.getCode(), stateCodeEnum.getDesc());
}
public ApiResult(T data) {
this(SellerCodeEnum.SUCCESS.getCode(), SellerCodeEnum.SUCCESS.getDesc(),data);
}
/**
* 判断是否成功
* 必须业务也返回成功
* @return
*/
public Boolean isSuccess() {
return code.equals(SellerCodeEnum.SUCCESS.getCode());
}
}
12.解耦转换类举例
package com.zj.sellermanager.web.convert;
import com.google.common.collect.Lists;
import com.zj.sellermanager.biz.service.CategoryService;
import com.zj.sellermanager.entity.Category;
import com.zj.sellermanager.web.vo.CategoryVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import java.util.Collections;
import java.util.List;
public class CategoryConvertUtils {
@Autowired
private CategoryService categoryService;
public static CategoryVo convertCategoryVo(Category category){
if(category == null){
return null;
}
CategoryVo categoryVo = new CategoryVo();
BeanUtils.copyProperties(category,categoryVo);
return categoryVo;
}
public static List<CategoryVo> convertCategoryVoList(List<Category> categoryList){
if(CollectionUtils.isEmpty(categoryList)){
return Collections.EMPTY_LIST;
}
List<CategoryVo> categoryVoList = Lists.newArrayList();
for (Category category:categoryList) {
categoryVoList.add(convertCategoryVo(category));
}
return categoryVoList;
}
}