- 一.详解
- 1.业务需求:
- 2.解决思路:
- 二.实例
- controller:
- serviceImpl 类
- mapper:
- Mapper.xml:
- 以下是实体类:
业务为 个人重大事项报告 和 单位重大事项报告 两种。业务类似于:发起办公流程-》部门领导审核-》报备给单位领导。流程发起时,两种流程时分开发起的,所以设计时设计了两张表来记录两种业务。流程发起、审核、报备,设计的是完全独立的。后来由于甲方的脑残需求,要求在单位领导查看报备报备信息时,两张业务合并在一个列表里,并且要按时间排序,要有分页。
2.解决思路:自定义sql,利用union
将两张业务表的公共字段 合并成一个虚拟表
(
SELECT
gaform_lpt_30.file_id file_id,
gaform_lpt_30.unit unit,
gaform_lpt_30.`name` `name`,
gaform_lpt_30.gettime time
FROM
`gaform_lpt_30`
WHERE
allagree = 1
) UNION ALL
(
SELECT
gaform_lpt_29.file_id file_id,
gaform_lpt_29.report_unit unit,
gaform_lpt_29.`report_name` `name`,
gaform_lpt_29.gettime time
FROM
`gaform_lpt_29`
WHERE
allagree = 1
)
然后在上面union结果的外层套上排序
这里需要注意一下: 合并 union两边的数据列数(as的字段列)必须一致,否则会合并失败
SELECT
*
FROM
(
(
SELECT
gaform_lpt_30.file_id file_id,
gaform_lpt_30.unit unit,
gaform_lpt_30.`name` `name`,
gaform_lpt_30.gettime time
FROM
`gaform_lpt_30`
WHERE
allagree = 1
) UNION ALL
(
SELECT
gaform_lpt_29.file_id file_id,
gaform_lpt_29.report_unit unit,
gaform_lpt_29.`report_name` `name`,
gaform_lpt_29.gettime time
FROM
`gaform_lpt_29`
WHERE
allagree = 1
)
) AS t #此处一定注意,union后务必派生声明虚拟表,不然会出现报错
ORDER BY
time DESC #time是派生的虚拟表的字段
这时 排序和两表合并就完成了。分页利用mybatis
框架,只要给dao层方法正常传IPage就可以了(本来怎么分页,这里就可以直接接分页对象了)
以下是java代码:
controller层
@ApiOperation("报备列表-29+30共用")
@PostMapping("selectBblist")
public ServiceResult selectBblist(@RequestParam Integer page,@RequestParam Integer pageCount) {
IPage<Lpt2930BaobeiVO> page2= gaformLpt29Service.selectBb(page,pageCount);
return success(page2);
}
service层
@Override
public IPage<Lpt2930BaobeiVO> selectBb(Integer page, Integer pageCount) {
return gaformLpt29Dao.selectBb( new Page<>(page, pageCount));
}
dao层
(只是把上边的sql拿到了这里)
@Select("SELECT\n" +
"\t*\n" +
"FROM\n" +
"\t(\n" +
"\t\t( SELECT gaform_lpt_30.file_id file_id, gaform_lpt_30.unit unit, gaform_lpt_30.`name` `name`, gaform_lpt_30.gettime time ,gaform_lpt_30.event_id event_id FROM `gaform_lpt_30` WHERE allagree = 1 ) \n" +
"\t\tUNION ALL\n" +
"\t\t( SELECT gaform_lpt_29.file_id file_id, gaform_lpt_29.report_unit unit, gaform_lpt_29.`report_name` `name`, gaform_lpt_29.gettime time,gaform_lpt_29.event_id event_id FROM `gaform_lpt_29` WHERE allagree = 1 ) \n" +
"\n" +
") as t ORDER BY time DESC")
IPage<Lpt2930BaobeiVO> selectBb(IPage page);//此处传入page 插件会自动实现分页
接收数据的vo
@Data
public class Lpt2930BaobeiVO {
public String fileId;
public String unit;
public String name;
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
public Date time;
public String eventId;
}
原文链接:https://blog.csdn.net/qq_27037397/article/details/121329562
二.实例这里我把整个类(三个接口)贴过来了,很长,不过很贴近实际
package com.boot.reservation.controller.statistics;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.boot.reservation.entity.domain.vo.StatisticsGranaryWebsiteVO;
import com.boot.reservation.entity.domain.vo.StatisticsHouseDetailsWebsiteVO;
import com.boot.reservation.entity.domain.vo.StatisticsHouseWebsiteVO;
import com.boot.reservation.service.statistics.StatisticsWebsiteService;
import com.boot.reservation.util.PageResponse;
import com.boot.reservation.util.PageResponseUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@Api(tags = "网页统计功能接口")
@RestController
@RequestMapping("/statistics/website")
public class StatisticsWebsiteController {
protected Logger logger = LoggerFactory.getLogger(this.getClass());
@Autowired
private StatisticsWebsiteService statisticsWebsiteService;
/**
* 出入库统计 - 库列表
* @param query 条件query
* @return
*/
@ApiOperation("出入库统计-库")
@ApiResponses({
@ApiResponse(code = 200,message = "请求成功",response = StatisticsGranaryWebsiteVO.class)
})
@PostMapping(value = "/granary/list")
public PageResponse<StatisticsGranaryWebsiteVO> findGranaryByPage(@RequestBody StatisticsGranaryWebsiteVO query){
if (query == null) {
query = new StatisticsGranaryWebsiteVO();
logger.error("出入库统计-库列表查询:query: {}", query);
}
Page<StatisticsGranaryWebsiteVO> byPage = statisticsWebsiteService.findGranaryByPage(query);
logger.info("[{},{}], {}", byPage.getCurrent(), byPage.getSize(), byPage.getRecords());
return PageResponseUtil.toPageResponce(byPage);
}
/**
* 出入库统计 - 仓房列表
* @param query 条件query
* @return
*/
@ApiOperation("出入库统计 - 仓房列表")
@ApiResponses({
@ApiResponse(code = 200,message = "请求成功",response = StatisticsHouseWebsiteVO.class)
})
@PostMapping(value = "/house/list")
public PageResponse<StatisticsHouseWebsiteVO> findHouseByPage(@RequestBody StatisticsHouseWebsiteVO query){
if (query == null) {
query = new StatisticsHouseWebsiteVO();
logger.error("出入库统计-库列表查询:query: {}", query);
}
if (StringUtils.isBlank(query.getGranaryAddress())) {
Page<StatisticsHouseWebsiteVO> voPage = new Page<>();
return PageResponseUtil.toPageResponce(voPage);
}
Page<StatisticsHouseWebsiteVO> byPage = statisticsWebsiteService.findHouseByPage(query);
logger.info("[{},{}], {}", byPage.getCurrent(), byPage.getSize(), byPage.getRecords());
return PageResponseUtil.toPageResponce(byPage);
}
/**
* 出入库统计 - 仓房查看列表
* @param query 条件query
* @return
*/
@ApiOperation("出入库统计 - 仓房查看列表")
@ApiResponses({
@ApiResponse(code = 200,message = "请求成功",response = StatisticsHouseDetailsWebsiteVO.class)
})
@PostMapping(value = "/houseDetails/list")
public PageResponse<StatisticsHouseDetailsWebsiteVO> findHouseDetailsByPage(@RequestBody StatisticsHouseDetailsWebsiteVO query){
if (query == null) {
query = new StatisticsHouseDetailsWebsiteVO();
logger.error("出入库统计-库列表查询:query: {}", query);
}
if (StringUtils.isBlank(query.getHouse())) {
Page<StatisticsHouseDetailsWebsiteVO> voPage = new Page<>();
return PageResponseUtil.toPageResponce(voPage);
}
Page<StatisticsHouseDetailsWebsiteVO> byPage = statisticsWebsiteService.findHouseDetailsByPage(query);
logger.info("[{},{}], {}", byPage.getCurrent(), byPage.getSize(), byPage.getRecords());
return PageResponseUtil.toPageResponce(byPage);
}
}
serviceImpl 类
package com.boot.reservation.impl.statistics;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.boot.reservation.entity.domain.InStock;
import com.boot.reservation.entity.domain.vo.StatisticsGranaryWebsiteVO;
import com.boot.reservation.entity.domain.vo.StatisticsHouseDetailsWebsiteVO;
import com.boot.reservation.entity.domain.vo.StatisticsHouseWebsiteVO;
import com.boot.reservation.entity.domain.vo.StorageInfoVO;
import com.boot.reservation.mapper.StatisticsAppletMapper;
import com.boot.reservation.mapper.StatisticsWebsiteMapper;
import com.boot.reservation.mapper.StorageInStockMapper;
import com.boot.reservation.service.project.ProjectManagerService;
import com.boot.reservation.service.statistics.StatisticsWebsiteService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import java.math.BigDecimal;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;
@Service
public class StatisticsWebsiteServiceImpl implements StatisticsWebsiteService {
protected Logger logger = LoggerFactory.getLogger(this.getClass());
@Autowired
private StatisticsWebsiteMapper statisticsWebsiteMapper;
@Autowired
private UserSessionRedisUtil userSessionRedisUtil;
@Value("${authentication.switch}")
private Boolean isSwitch;
@Autowired
private ProjectManagerService projectManagerService;
@Autowired
private StatisticsAppletMapper statisticsAppletMapper;
@Autowired
private StorageInStockMapper storageInStockMapper;
@Override
public Page<StatisticsGranaryWebsiteVO> findGranaryByPage(StatisticsGranaryWebsiteVO query) {
List<String> storageCodeList = toDataPowerList();
Page<StatisticsGranaryWebsiteVO> granaryByPage = statisticsWebsiteMapper.findGranaryByPage(query, toDataPowerList());
List<StatisticsGranaryWebsiteVO> records = granaryByPage.getRecords();
if (records != null && records.size() > 0) {
for (StatisticsGranaryWebsiteVO record : records) {
Double alreadyOutStock = statisticsAppletMapper.findAlreadyOutStock(record.getGranaryAddress(), storageCodeList);
Double practicalOutStock = statisticsAppletMapper.findPracticalOutStock(record.getGranaryAddress(), "", storageCodeList);
record.setResidueOutStockNum(BigDecimal.valueOf(alreadyOutStock).subtract(BigDecimal.valueOf(practicalOutStock)).doubleValue());
record.setGrandTotalNum(BigDecimal.valueOf(record.getGrandTotalInStockNum()).subtract(BigDecimal.valueOf(record.getGrandTotalOutStockNum())).doubleValue());
}
}
return granaryByPage;
}
@Override
public Page<StatisticsHouseWebsiteVO> findHouseByPage(StatisticsHouseWebsiteVO query) {
Page<StatisticsHouseWebsiteVO> houseByPage = statisticsWebsiteMapper.findHouseByPage(query);
List<StatisticsHouseWebsiteVO> records = houseByPage.getRecords();
if (records != null && records.size() > 0) {
for (StatisticsHouseWebsiteVO record : records) {
Double houseAlreadyOutStock = statisticsAppletMapper.findHouseAlreadyOutStock(record.getGranaryAddress(), record.getHouse(),null);
Double practicalOutStock = statisticsAppletMapper.findPracticalOutStock(record.getGranaryAddress(), record.getHouse(),null);
record.setResidueOutStockNum(BigDecimal.valueOf(houseAlreadyOutStock).subtract(BigDecimal.valueOf(practicalOutStock)).doubleValue());
record.setGrandTotalNum(BigDecimal.valueOf(record.getGrandTotalInStockNum()).subtract(BigDecimal.valueOf(record.getGrandTotalOutStockNum())).doubleValue());
QueryWrapper<InStock> inStockQueryWrapper = new QueryWrapper<>();
inStockQueryWrapper.select("kind_name")
.eq("granary_address",record.getGranaryAddress())
.eq("house",record.getHouse())
.eq("status", 02);
List<InStock> inStocks = storageInStockMapper.selectList(inStockQueryWrapper);
if (inStocks != null && inStocks.size() > 0) {
record.setKindName(inStocks.get(0).getKindName());
}
}
}
return houseByPage;
}
@Override
public Page<StatisticsHouseDetailsWebsiteVO> findHouseDetailsByPage(StatisticsHouseDetailsWebsiteVO query) {
Page<StatisticsHouseDetailsWebsiteVO> houseDetailsByPage = statisticsWebsiteMapper.findHouseDetailsByPage(query);
List<StatisticsHouseDetailsWebsiteVO> records = houseDetailsByPage.getRecords();
if (records != null && records.size() > 0) {
for (StatisticsHouseDetailsWebsiteVO record : records) {
if ("入库".equalsIgnoreCase(record.getBusinessType())) {
record.setWeight(
BigDecimal.valueOf(record.getGrossWeight())
.subtract(BigDecimal.valueOf(record.getBareWeight()))
.subtract(BigDecimal.valueOf(record.getRealityReduceWeight()))
);
} else {
record.setWeight(
BigDecimal.valueOf(record.getGrossWeight())
.subtract(BigDecimal.valueOf(record.getBareWeight()))
);
}
}
}
return houseDetailsByPage;
}
// 获取数据权限
private List<String> toDataPowerList(){
PerFrontUserEntity pu = userSessionRedisUtil.getSessionUserObjInfo();
List<StorageInfoVO> storages = new LinkedList<>();//库点列表
if (!isSwitch || pu == null) {
storages = projectManagerService.queryStoragesNoUser();
} else {
storages = projectManagerService.queryStoragesHasUser(String.valueOf(pu.getId()));
}
List<String> storageCodeList = storages.stream().map(StorageInfoVO::getStorageCode).collect(Collectors.toList());
return storageCodeList;
}
}
mapper:
package com.boot.reservation.mapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.boot.reservation.entity.domain.vo.StatisticsGranaryWebsiteVO;
import com.boot.reservation.entity.domain.vo.StatisticsHouseDetailsWebsiteVO;
import com.boot.reservation.entity.domain.vo.StatisticsHouseWebsiteVO;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Repository;
import java.util.List;
@Mapper
@Repository
public interface StatisticsWebsiteMapper {
Page<StatisticsGranaryWebsiteVO> findGranaryByPage(@Param("query") StatisticsGranaryWebsiteVO query, List<String> storageCodeList);
Page<StatisticsHouseWebsiteVO> findHouseByPage(@Param("query") StatisticsHouseWebsiteVO query);
Page<StatisticsHouseDetailsWebsiteVO> findHouseDetailsByPage(@Param("query") StatisticsHouseDetailsWebsiteVO query);
}
Mapper.xml:
DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.boot.reservation.mapper.StatisticsWebsiteMapper">
<select id="findGranaryByPage"
parameterType="com.boot.reservation.entity.domain.vo.StatisticsGranaryWebsiteVO"
resultType="com.boot.reservation.entity.domain.vo.StatisticsGranaryWebsiteVO">
select sins.granary_address as granaryAddress,
(select lps.storage_name from lp_project_storage lps where lps.storage_code = sins.granary_address) as granaryAddressName,
ifnull(sum(sins.settlement_num),0) as grandTotalInStockNum,
ifnull(sum(souts.gross_weight),0) as grandTotalOutStockNum,
ifnull(sum(lcl.lading_Quality),0) as grandTotalRelieveNum
from storage_in_stock sins
left join storage_out_stock souts on (sins.granary_address = souts.granary_address and souts.status = 02)
left join storage_receipt sr on sins.granary_address = sr.granary_address
left join storage_pledge sp on (sr.receipt_serial_num = sp.receipt_serial_num and sp.status = 02)
left join lp_collateral_list lcl on sp.pledge_serial_num = lcl.pledge_number
where sins.status = 02
<if test="storageCodeList != null and storageCodeList.size>0">
and sins.granary_address in
<foreach collection="storageCodeList" item="granaryAddress" open="(" separator="," close=")">
#{granaryAddress}
foreach>
if>
group by sins.granary_address
select>
<select id="findHouseByPage"
parameterType="com.boot.reservation.entity.domain.vo.StatisticsHouseWebsiteVO"
resultType="com.boot.reservation.entity.domain.vo.StatisticsHouseWebsiteVO">
select sins.granary_address as granaryAddress,
sins.house as house,
(select lps.storehouse_name from lp_project_storagehouse lps where lps.storehouse_code = sins.house) as houseName,
ifnull(sum(sins.settlement_num),0) as grandTotalInStockNum,
ifnull(sum(souts.gross_weight),0) as grandTotalOutStockNum,
ifnull(sum(lcl.lading_Quality),0) as grandTotalRelieveNum
from storage_in_stock sins
left join storage_out_stock souts on (sins.house = souts.house and souts.status = 02)
left join storage_receipt sr on sins.house = sr.house
left join storage_pledge sp on (sr.receipt_serial_num = sp.receipt_serial_num and sp.status = 02)
left join lp_collateral_list lcl on sp.pledge_serial_num = lcl.pledge_number
where sins.status = 02
<if test="query.granaryAddress != null and query.granaryAddress != ''">
and sins.granary_address = #{query.granaryAddress}
if>
group by sins.house
select>
<select id="findHouseDetailsByPage"
parameterType="com.boot.reservation.entity.domain.vo.StatisticsHouseDetailsWebsiteVO"
resultType="com.boot.reservation.entity.domain.vo.StatisticsHouseDetailsWebsiteVO">
select
*
from
(
(select sins.house as house,
sins.in_stock_serial_num as serialNumber,
'入库' as businessType,
sins.unload_end_time as time,
sins.kind_name as kindName,
sins.gross_weight as grossWeight,
sins.bare_weight as bareWeight,
sins.reality_reduce_weight as realityReduceWeight
from storage_in_stock sins
where sins.status = 02
<if test="query.house != null and query.house != ''">
and sins.house = #{query.house}
if>)
UNION ALL
(select souts.house as house,
souts.out_stock_serial_num as serialNumber,
'出库' as businessType,
souts.load_end_time as time,
souts.goods_location as kindName,
souts.gross_weight as grossWeight,
souts.bare_weight as bareWeight,
0.0 as realityReduceWeight
from storage_out_stock souts
where souts.status = 02
<if test="query.house != null and query.house != ''">
and souts.house = #{query.house}
if>)
) as shdw
ORDER BY time desc
select>
mapper>
以下是实体类:
package com.boot.reservation.entity.domain.vo;
import java.math.BigDecimal;
import java.util.Date;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.boot.reservation.entity.domain.DictValue;
import com.fasterxml.jackson.annotation.JsonFormat;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.io.Serializable;
/**
* 仓房明细查看统计VO
*/
@Data
@ApiModel("仓房明细查看统计VO")
public class StatisticsHouseDetailsWebsiteVO extends Page implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 仓房编码
*/
@ApiModelProperty("仓房编码")
private String house;
/**
* 流水号
*/
@ApiModelProperty("流水号")
private String serialNumber;
/**
* 业务类型
*/
@ApiModelProperty("业务类型")
private String businessType;
/**
* 时间
*/
@ApiModelProperty("时间")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private Date time;
/**
* 商品名称
*/
@ApiModelProperty("商品名称")
@DictValue(dictCode = "cargoType")
private String kindName;
/**
* 商品净重
*/
@ApiModelProperty("商品净重")
private BigDecimal weight;
/**
* 毛重 - 与前端无关
*/
@ApiModelProperty("毛重 - 与前端无关")
private Double grossWeight;
/**
* 皮重 - 与前端无关
*/
@ApiModelProperty("皮重 - 与前端无关")
private Double bareWeight;
/**
* 实际扣量 - 与前端无关
*/
@ApiModelProperty("实际扣量 - 与前端无关")
private Double realityReduceWeight;
}
package com.boot.reservation.entity.domain.vo;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.io.Serializable;
/**
* 库点统计VO
*/
@Data
@ApiModel("库点统计VO")
public class StatisticsGranaryWebsiteVO extends Page implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 库点编号
*/
@ApiModelProperty("库点编号")
private String granaryAddress;
/**
* 库点名称
*/
@ApiModelProperty("库点名称")
private String granaryAddressName;
/**
* 累计入库数量(kg)
*/
@ApiModelProperty("累计入库数量(kg)")
private Double grandTotalInStockNum;
/**
* 累计出库数量(kg)
*/
@ApiModelProperty("累计出库数量(kg)")
private Double grandTotalOutStockNum;
/**
* 累计解压数量(kg)
*/
@ApiModelProperty("累计解压数量(kg)")
private Double grandTotalRelieveNum;
/**
* 剩余可出库数量(kg)
*/
@ApiModelProperty("剩余可出库数量(kg)")
private Double residueOutStockNum;
/**
* 库存数量(kg)
*/
@ApiModelProperty("库存数量(kg)")
private Double grandTotalNum;
}
package com.boot.reservation.entity.domain.vo;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.boot.reservation.entity.domain.DictValue;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.io.Serializable;
/**
* 仓房统计VO
*/
@Data
@ApiModel("仓房统计VO")
public class StatisticsHouseWebsiteVO extends Page implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 库点编号
*/
@ApiModelProperty("库点编号")
private String granaryAddress;
/**
* 仓房编码
*/
@ApiModelProperty("库点编号")
private String house;
/**
* 仓房名称
*/
@ApiModelProperty("仓房名称")
private String houseName;
/**
* 商品名称
*/
@ApiModelProperty("商品名称")
@DictValue(dictCode = "cargoType")
private String kindName;
/**
* 累计入库数量(kg)
*/
@ApiModelProperty("累计入库数量(kg)")
private Double grandTotalInStockNum;
/**
* 累计出库数量(kg)
*/
@ApiModelProperty("累计出库数量(kg)")
private Double grandTotalOutStockNum;
/**
* 累计解压数量(kg)
*/
@ApiModelProperty("累计解压数量(kg)")
private Double grandTotalRelieveNum;
/**
* 剩余可出库数量(kg)
*/
@ApiModelProperty("剩余可出库数量(kg)")
private Double residueOutStockNum;
/**
* 库存数量(kg)
*/
@ApiModelProperty("库存数量(kg)")
private Double grandTotalNum;
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)