java+postgresql+swagger-多表关联insert操作(九)
入参为json,然后根据需要对多张表进行操作:
入参格式:
{"username": "车主01","usertel": "11111111111","useridtype": "2","useridcard": null,"proname": "天津市","cityname": "天津市市辖区","vinnumber": "2222222222","platenumber": "","cartype": "1","renttype": null,"totalperiods": null,"risklevel": null,"riskcontrolscore": null,"contractno": "","userclasstype": "6","overdueperiods": null,"loandate": null,"endrenttime": null,"inputtime": "2025-04-17T11:33:35","jsonreport": null,"createdbyid": "00000000-0000-0000-0000-000000000000","custstoreName":"swagger-测试经销商01","customerName":"swagger-测试客户01","applyid": "1111111111","credittype": null,"projectprocess": null,"yuqiperiod": null,"settledstatus": null,"startoffline": null,"endoffline": null,"offlineduration": null,"carmodel": "宝马8座 手动 1.5","carseries": "冷藏车老司e","carbrand": "澳柯玛增福改一下22","enginenumber": "","cooperativeunit": null,"lendtime": null,"devicenumber": "987654321","devicemodel": "ZRA5N-8-2","simnumber": "123456789","iswireless": "有线","installposition": "后备箱右侧","installtime": "2025-04-17 13:15:31","supplierid": "测试供应商01","suppliercode": "00001","displaystatus": 2,"simkinds": 1,"installproname": "新疆维吾尔自治区","installcityname": "阿克苏地区","installdistname": "温宿县","installlat": null,"installlng": null,"installperson": "XX000000","simservicecycle": null,"isdisplay": 0,"hosttype": null}
分别往下面表进行写数:
tb_custstoreinfo、tb_supplierinfo、tb_caruserinfo、tb_carusersecondaryinfo、tb_deviceinfo
1、实体:
1.1、表实体:
省略
1.2、入参实体:
package com.example.springbootmybatisplus.dto;import lombok.Data;import java.math.BigDecimal;
import java.util.Date;@Data
public class CarUserDto {private String userName;private String userTel;private String userIdType;private String userIdCard;private String proName;private String cityName;private String vinNumber;private String plateNumber;private String carType;private String rentType;private Integer totalPeriods;private Integer riskLevel;private BigDecimal riskControlScore;private String contractNo;private String userClassType;private String overduePeriods;private Date loanDate;private Date endRentTime;private Date inputTime;private String jsonReport;private String createdById;private String custStoreName;private String customerName;private String applyId;private Integer creditType;private String projectProcess;private String yuqiPeriod;private String settledStatus;private String startOffline;private String endOffline;private BigDecimal offlineDuration;private String carModel;private String carSeries;private String carBrand;private String engineNumber;private String cooperativeUnit;private Date lendTime;private String deviceNumber;private String deviceModel;private String simNumber;private String isWireless;private String installPosition;private Date installTime;private String supplierId;private Short displayStatus;private Short simKinds;private String installProName;private String installCityName;private String installDistName;private BigDecimal installLat;private BigDecimal installLng;private String installPerson;private Short simServiceCycle;private Integer isDisplay;private Integer hostType;private String supplierCode;
}
1.3、其他中间实体:
package com.example.springbootmybatisplus.dto;import lombok.Data;@Data
public class DistrictDto {private String proCode;private String proName;private String cityCode;private String cityName;private String lat;private String lng;
}
package com.example.springbootmybatisplus.entity;import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import lombok.Data;import java.io.Serializable;
@Data
public class TbCustStore implements Serializable {/*** 主键(DL)*/@TableId(value = "id", type = IdType.INPUT)private String id;/*** 客户Id*/@TableField(value = "customerid")private String customerId;/*** 上级经销商Id*/@TableField(value = "parentId")private String parentId;/*** 经销商编号*/@TableField(value = "code")private String code;/*** 经销商名称*/@TableField(value = "\"name\"")private String name;/*** 经销商等级*/@TableField(value = "levelCode")private Short levelCode;
}
2、Mapper:
package com.example.springbootmybatisplus.mapper;import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.example.springbootmybatisplus.entity.TbCarUserInfo;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;@Mapper
public interface TbCarUserInfoMapper extends BaseMapper<TbCarUserInfo> {@Select("select Id as carid from tb_caruserinfo where vinnumber = #{vinNumber} and deleted=false limit 1")String getCarId(@Param("vinNumber") String vinNumber);@Select("select 'TC'||nextval('tc')")String getCarUserInfoId();
}
package com.example.springbootmybatisplus.mapper;import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.example.springbootmybatisplus.entity.TbCarUserSecondaryInfo;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;@Mapper
public interface TbCarUserSecondaryInfoMapper extends BaseMapper<TbCarUserSecondaryInfo> {@Select("select 'CD'||nextval('cd')")String getCarUserSecondaryInfoId();
}
package com.example.springbootmybatisplus.mapper;import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.example.springbootmybatisplus.entity.TbDeviceInfo;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;@Mapper
public interface TbDeviceInfoMapper extends BaseMapper<TbDeviceInfo> {@Select("select id as DeviceId from tb_deviceinfo where devicenumber = #{deviceNumber} and deleted=false ")String getDeviceId(@Param("deviceNumber") String deviceNumber);@Select("select 'DI'||nextval('di')")String getDeviceInfoId();
}
package com.example.springbootmybatisplus.mapper;import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.example.springbootmybatisplus.entity.TbSupplierinfo;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;@Mapper
public interface TbSupplierinfoMapper extends BaseMapper<TbSupplierinfo> {@Select("select * from tb_supplierinfo where name = #{name} and deleted=false limit 1")TbSupplierinfo getSupplierId(@Param("name") String name);@Select("select 'SU'||nextval('su')")String getSupplierinfoId();
}
3、Service:
3.1、对经销商信息进行处理的Service:
package com.example.springbootmybatisplus.service.impl;import com.example.springbootmybatisplus.entity.TbCustStore;
import com.example.springbootmybatisplus.entity.TbCustStoreInfo;
import com.example.springbootmybatisplus.mapper.TbCustStoreInfoMapper;
import com.example.springbootmybatisplus.service.TbPropertyService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;import java.util.Date;
import java.util.Objects;
import java.util.UUID;@Service
public class StoreInfoService {private static final Logger log = LoggerFactory.getLogger(TbPropertyService.class);@Autowiredprivate TbCustStoreInfoMapper tbCustStoreInfoMapper;public void addCustSore(String inCustName, String inCustStoreName, Integer num) {try {if (inCustName == null && inCustStoreName == null) {log.info("输入的经销商或客户名称为空");} else {if (num == 1) {TbCustStore existCustomerId = tbCustStoreInfoMapper.selectTbCustStoreInfo3(inCustName);if (Objects.isNull(existCustomerId)) {log.info("该客户在库中不存在,需要新建");TbCustStoreInfo tbCustStoreInfo = insertTbCustomerInfo(inCustName, 1);tbCustStoreInfoMapper.insert(tbCustStoreInfo);} else {log.info("该客户:{}在库中已存在", inCustName);}}if (num == 2) {TbCustStore existCustStoreId = tbCustStoreInfoMapper.selectTbCustStoreInfo3(inCustStoreName);if (Objects.isNull(existCustStoreId)) {log.info("该经销商在库中不存在,需要新建");TbCustStoreInfo cc = new TbCustStoreInfo();TbCustStore tbCustStore = tbCustStoreInfoMapper.selectTbCustStoreInfo3(inCustName);cc.setId(UUID.randomUUID().toString());cc.setCustomerId((tbCustStore.getCustomerId()));cc.setParentId(tbCustStore.getId());cc.setCustomerdealerid(tbCustStore.getId());cc.setCode(tbCustStoreInfoMapper.getCustStoreCode(tbCustStore.getId()));cc.setLevelCode((short) (tbCustStore.getLevelCode() + 1));cc.setName(inCustStoreName);cc.setType(2);cc.setInsertTime(new Date());tbCustStoreInfoMapper.insert(cc);} else {log.info("该经销商:{}在库中已存在", inCustStoreName);}}}} catch (Exception e) {log.error("异常信息:" + e.getMessage());}}public TbCustStoreInfo insertTbCustomerInfo(String inCustName, Integer num) {TbCustStoreInfo bb = new TbCustStoreInfo();String inId = UUID.randomUUID().toString();bb.setId(inId);bb.setCustomerId(inId);bb.setParentId("DL9999999997");bb.setCustomerdealerid(inId);bb.setCode(tbCustStoreInfoMapper.getCustStoreCode("DL9999999997"));bb.setLevelCode(Short.parseShort("2"));bb.setName(inCustName);bb.setType(2);bb.setInsertTime(new Date());return bb;}}
3.2、对供应商进行处理的Service:
package com.example.springbootmybatisplus.service.impl;import com.example.springbootmybatisplus.entity.TbSupplierinfo;
import com.example.springbootmybatisplus.mapper.TbSupplierinfoMapper;
import com.example.springbootmybatisplus.service.TbPropertyService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;import java.util.Date;
import java.util.Objects;@Service
public class SupplierInfoService {private static final Logger log = LoggerFactory.getLogger(TbPropertyService.class);@Autowiredprivate TbSupplierinfoMapper tbSupplierinfoMapper;public void addSupplier(String msg, String code) {try {if (msg == null) {log.info("输入的供应商为空");} else {TbSupplierinfo existsTbSupplierinfo = tbSupplierinfoMapper.getSupplierId(msg);if (Objects.isNull(existsTbSupplierinfo)) {log.info("该供应商在库中不存在,需要新建");TbSupplierinfo tbSupplierinfo = insertTbSupplierinfo(msg, code);tbSupplierinfoMapper.insert(tbSupplierinfo);} else {log.info("该供应商:{}在库中已存在", msg);}}} catch (Exception e) {log.error("异常信息:" + e.getMessage());}}public TbSupplierinfo insertTbSupplierinfo(String name, String code) {TbSupplierinfo tbSupplierinfo = new TbSupplierinfo();tbSupplierinfo.setId(tbSupplierinfoMapper.getSupplierinfoId());tbSupplierinfo.setName(name);tbSupplierinfo.setCode(code);tbSupplierinfo.setCreatedById("00000000-0000-0000-0000-000000000000");tbSupplierinfo.setCreatedAt(new Date());tbSupplierinfo.setDeleted(false);return tbSupplierinfo;}}
3.3、实现功能的Service:
package com.example.springbootmybatisplus.service;import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.springbootmybatisplus.dto.CarUserDto;
import com.example.springbootmybatisplus.dto.DistrictDto;
import com.example.springbootmybatisplus.entity.*;
import com.example.springbootmybatisplus.mapper.*;
import com.example.springbootmybatisplus.service.impl.StoreInfoService;
import com.example.springbootmybatisplus.service.impl.SupplierInfoService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;import java.util.Date;
import java.util.Objects;@Service
public class TbCarUserInfoService {private static final Logger log = LoggerFactory.getLogger(TbPropertyService.class);@Autowiredprivate CarUserMapper carUserMapper;@Autowiredprivate TbCarUserInfoMapper tbCarUserInfoMapper;@Autowiredprivate TbCarUserSecondaryInfoMapper tbCarUserSecondaryInfoMapper;@Autowiredprivate TbDeviceInfoMapper tbDeviceInfoMapper;@Autowiredprivate TbCustStoreInfoMapper tbCustStoreInfoMapper;@Autowiredprivate StoreInfoService storeInfoService;@Autowiredprivate TbDistrictMapper tbDistrictMapper;@Autowiredprivate TbSupplierinfoMapper tbSupplierinfoMapper;@Autowiredprivate SupplierInfoService supplierInfoService;public void addCarUser(String msg) {try {CarUserDto carUserDto = JSON.parseObject(msg, CarUserDto.class);if (Objects.isNull(carUserDto)) {log.info("车辆信息为空");return;}storeInfoService.addCustSore(carUserDto.getCustomerName(), carUserDto.getCustStoreName(), 1);storeInfoService.addCustSore(carUserDto.getCustomerName(), carUserDto.getCustStoreName(), 2);supplierInfoService.addSupplier(carUserDto.getSupplierId(), carUserDto.getSupplierCode());if (Objects.isNull(carUserDto.getVinNumber())) {log.error("输入的车架号为空,车架号为非空字段");} else {String existsCarId = tbCarUserInfoMapper.getCarId(carUserDto.getVinNumber());if (Objects.isNull(existsCarId)) {log.info("该车架号不存在系统中,需增加此车架号:{}的信息", carUserDto.getVinNumber());TbCarUserInfo tbCarUserInfo = insertTbCarUserInfo(carUserDto);tbCarUserInfoMapper.insert(tbCarUserInfo);TbCarUserSecondaryInfo tbCarUserSecondaryInfo = insertTbCarUserSecondaryInfo(carUserDto);tbCarUserSecondaryInfoMapper.insert(tbCarUserSecondaryInfo);} else {log.warn("输入的车架号:{}信息已在库中存在,不做任何处理!", carUserDto.getVinNumber());}String existsDeviceId = tbDeviceInfoMapper.getDeviceId(carUserDto.getDeviceNumber());if (Objects.isNull(existsDeviceId)) {log.info("该设备号不存在系统中,需增加此设备号:{}的信息", carUserDto.getDeviceNumber());TbDeviceInfo tbDeviceInfo = insertTbDeviceInfo(carUserDto);tbDeviceInfoMapper.insert(tbDeviceInfo);} else {log.warn("输入的设备号:{}信息已在库中存在,不做任何处理!", carUserDto.getDeviceNumber());}}} catch (Exception e) {log.error("异常信息:" + e.getMessage());}}public TbCarUserInfo insertTbCarUserInfo(CarUserDto carUserDto) {TbCarUserInfo tbCarUserInfo = new TbCarUserInfo();DistrictDto districtDto = tbDistrictMapper.selectProCodeAndCityCode(carUserDto.getProName(), carUserDto.getCityName());TbCustStore tbCustStore=tbCustStoreInfoMapper.selectTbCustStoreInfo3(carUserDto.getCustStoreName());tbCarUserInfo.setId(tbCarUserInfoMapper.getCarUserInfoId());tbCarUserInfo.setUserName(carUserDto.getUserName());tbCarUserInfo.setUserTel(carUserDto.getUserTel());tbCarUserInfo.setUserIdType(carUserDto.getUserIdType());tbCarUserInfo.setUserIdCard(carUserDto.getUserIdCard());tbCarUserInfo.setProName(carUserDto.getProName());tbCarUserInfo.setProCode(districtDto.getProCode());tbCarUserInfo.setCityName(carUserDto.getCityName());tbCarUserInfo.setCityCode(districtDto.getCityCode());tbCarUserInfo.setVinNumber(carUserDto.getVinNumber());tbCarUserInfo.setPlateNumber(carUserDto.getPlateNumber());tbCarUserInfo.setCarType(carUserDto.getCarType());tbCarUserInfo.setRentType(carUserDto.getRentType());tbCarUserInfo.setTotalPeriods(carUserDto.getTotalPeriods());tbCarUserInfo.setRiskLevel(carUserDto.getRiskLevel());tbCarUserInfo.setRiskControlScore(carUserDto.getRiskControlScore());tbCarUserInfo.setContractNo(carUserDto.getContractNo());tbCarUserInfo.setUserClassType(carUserDto.getUserClassType());tbCarUserInfo.setOverduePeriods(carUserDto.getOverduePeriods());tbCarUserInfo.setLoanDate(carUserDto.getLoanDate() != null ? carUserDto.getLoanDate() : new Date());tbCarUserInfo.setEndRentTime(carUserDto.getEndRentTime());tbCarUserInfo.setInputTime(carUserDto.getInputTime() != null ? carUserDto.getInputTime() : new Date());tbCarUserInfo.setJsonReport(carUserDto.getJsonReport());tbCarUserInfo.setCreatedById("00000000-0000-0000-0000-000000000000");tbCarUserInfo.setCustomerId(tbCustStore.getCustomerId());tbCarUserInfo.setCuststoreId(tbCustStore.getId());tbCarUserInfo.setApplyId(carUserDto.getApplyId());tbCarUserInfo.setCreditType(carUserDto.getCreditType());tbCarUserInfo.setProjectProcess(carUserDto.getProjectProcess());tbCarUserInfo.setJsonString(JSONObject.toJSONString(carUserDto));tbCarUserInfo.setCreatedAt(new Date());tbCarUserInfo.setDeleted(false);return tbCarUserInfo;}public TbCarUserSecondaryInfo insertTbCarUserSecondaryInfo(CarUserDto carUserDto) {TbCarUserSecondaryInfo tbCarUserSecondaryInfo = new TbCarUserSecondaryInfo();tbCarUserSecondaryInfo.setId(tbCarUserSecondaryInfoMapper.getCarUserSecondaryInfoId());tbCarUserSecondaryInfo.setCarId(tbCarUserInfoMapper.getCarId(carUserDto.getVinNumber()));tbCarUserSecondaryInfo.setYuqiPeriod(carUserDto.getYuqiPeriod());tbCarUserSecondaryInfo.setSettledStatus(carUserDto.getSettledStatus());tbCarUserSecondaryInfo.setStartOffline(carUserDto.getStartOffline());tbCarUserSecondaryInfo.setEndOffline(carUserDto.getEndOffline());tbCarUserSecondaryInfo.setOfflineDuration(carUserDto.getOfflineDuration());tbCarUserSecondaryInfo.setCarModel(carUserDto.getCarModel());tbCarUserSecondaryInfo.setCarSeries(carUserDto.getCarSeries());tbCarUserSecondaryInfo.setCarBrand(carUserDto.getCarBrand());tbCarUserSecondaryInfo.setEngineNumber(carUserDto.getEngineNumber());tbCarUserSecondaryInfo.setCooperativeUnit(carUserDto.getCooperativeUnit());tbCarUserSecondaryInfo.setLendTime(carUserDto.getLendTime() != null ? carUserDto.getLendTime() : new Date());tbCarUserSecondaryInfo.setCreatedById("00000000-0000-0000-0000-000000000000");tbCarUserSecondaryInfo.setCreatedAt(new Date());tbCarUserSecondaryInfo.setDeleted(false);return tbCarUserSecondaryInfo;}public TbDeviceInfo insertTbDeviceInfo(CarUserDto carUserDto) {TbDeviceInfo tbDeviceInfo = new TbDeviceInfo();tbDeviceInfo.setId(tbDeviceInfoMapper.getDeviceInfoId());tbDeviceInfo.setCarId(tbCarUserInfoMapper.getCarId(carUserDto.getVinNumber()));tbDeviceInfo.setDeviceNumber(carUserDto.getDeviceNumber());tbDeviceInfo.setDeviceModel(carUserDto.getDeviceModel());tbDeviceInfo.setSimNumber(carUserDto.getSimNumber());String isWireless = carUserDto.getIsWireless();if ("有线".equals(isWireless)) {tbDeviceInfo.setIsWireless(Short.parseShort("0"));} else if ("无线".equals(isWireless)) {tbDeviceInfo.setIsWireless(Short.parseShort("1"));} else {tbDeviceInfo.setIsWireless(Short.parseShort("2"));}tbDeviceInfo.setInstallPosition(carUserDto.getInstallPosition());tbDeviceInfo.setInstallTime(carUserDto.getInstallTime());tbDeviceInfo.setSupplierid(tbSupplierinfoMapper.getSupplierId(carUserDto.getSupplierId()).getId());tbDeviceInfo.setDisplaystatus(carUserDto.getDisplayStatus());tbDeviceInfo.setSimkinds(carUserDto.getSimKinds());DistrictDto districtDto = tbDistrictMapper.selectProCodeAndCityCode(carUserDto.getInstallProName(), carUserDto.getInstallCityName());if (Objects.isNull(districtDto)){log.warn("未找到对应的省:{}和市:{}的code",carUserDto.getInstallProName(),carUserDto.getInstallCityName());}else {tbDeviceInfo.setInstallProCode(districtDto.getProCode());tbDeviceInfo.setInstallCityCode(districtDto.getCityCode());}tbDeviceInfo.setInstallProName(carUserDto.getInstallProName());tbDeviceInfo.setInstallCityName(carUserDto.getInstallCityName());DistrictDto districtDto1 = tbDistrictMapper.selectProCodeAndCityCode(carUserDto.getInstallCityName(), carUserDto.getInstallDistName());if (Objects.isNull(districtDto1)){log.warn("未找到对应的市:{}和区县:{}的code",carUserDto.getInstallCityName(),carUserDto.getInstallDistName());}else {tbDeviceInfo.setInstallDistCode(districtDto1.getCityCode());}tbDeviceInfo.setInstallDistName(carUserDto.getInstallDistName());tbDeviceInfo.setInstallLat(carUserDto.getInstallLat());tbDeviceInfo.setInstallLng(carUserDto.getInstallLng());tbDeviceInfo.setInstallPerson(carUserDto.getInstallPerson());tbDeviceInfo.setSimServiceCycle(carUserDto.getSimServiceCycle());tbDeviceInfo.setIsDisplay(carUserDto.getDisplayStatus());tbDeviceInfo.setHostType(carUserDto.getHostType());tbDeviceInfo.setCreatedByid("00000000-0000-0000-0000-000000000000");tbDeviceInfo.setCreatedAt(new Date());tbDeviceInfo.setDeleted(false);return tbDeviceInfo;}}
4、Controller:
package com.example.springbootmybatisplus.contronller;import com.example.springbootmybatisplus.service.TbCarUserInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;@Controller
public class TbCarUserInfoController {@Autowiredprivate TbCarUserInfoService tbCarUserInfoService;@PostMapping("/insert1")public ResponseEntity<String> insert1(@RequestBody String msg) {try {tbCarUserInfoService.addCarUser(msg);return ResponseEntity.status(HttpStatus.CREATED).body("Success");} catch (Exception e) {return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Failed");}}
}