当前位置:首页>java>私人代码收藏

私人代码收藏

  • 2026-10-21 13:28:19
私人代码收藏

点击关注公众号,Java干货及时送达👇

  • 1、代码lambdaQueryWrapper拼接sql查询
  • 2、字符串前面补0
  • 3、文件下载
  • 4、普通下载方法
  • 5、文件导入
  • 6、求两个string日期中间的时间
  • 7、对象拷贝
  • 8、生成uuid
  • 9、实体类日期格式处理
  • 10、文件打成zip
  • 11、判断字符串最后一个字符
  • 12、list互转json、string
  • 13、实体类或者任何对象空值不返回注解和忽略注解
  • 14、mybatisplus后台向前端传输long精度丢失问题
  • 15、数组自动排序
  • 16、mybatis的@Select()注解用法
  • 17、mybatis更新null不生效
  • 18、判断异常是否属于ICBCException
  • 19、mybatisplus-distinct用法
  • 20、EasyExcel自定义模板填充下载
  • 21、mybatisplus-and()or()用法
  • 22、下拉框列表查询
  • 23、mybatisplus、paas云日志Sql不打印问题
  • 24、判断对象或者字符串是否为nuLl
1、代码lambdaQueryWrapper拼接sql查询
public List< CreditquotaEntity> queryDataConfirm(CreditquotaEntity creditquota) {
    LambdaQueryWrapper<CreditquotaEntity> warp = new LambdaQueryWrapper<>();
    if(StringUtils,isNotEmpty(creditquota.getCustno()) warp.eq(CreditquotaEntity:getCustno,creditquota.getCustno());
    if(StringUtils,isNotEmpty(creditquota.getCustName())) warp.eq(CreditquotaEntity:getCustName,creditquota.getCustName());
    //数据权限筛选String zoneno =ZxdUtils.getCurrUserZonenoAndBrno0.get("zoneno");
        String brno =ZxdUtils.getCurrUserZonenoAndBrno0.get(brno");
        if(!1700"
.equals(zoneno) && !"01700".equals(zoneno)){
            warp.eq(CreditquotaEntity:getZoneno,zoneno);
            if(!"0000".equals(brno)) warp.eq(CreditquotaEntity::getBrno,brno);
        }
        warp.eq(CreditquotaEntity:getEmail,"").or(item -> item.eq(CreditquotaEntity::getEmail,nul);
        warp.and((item -> item.eq(CreditquotaEntity:getEmail,"").or().isNull(CreditquotaEntity:getEmail);
        warp.apply("(email =" OR email is null)");
        List<CreditquotaEntity> entities = this.list(warp);
        entities.forEach(entity->{
            entity.setMobile(DataMaskUtil.mobilePhone(entity.getMobile0));
            entity.setCertCode(DataMaskUtil.idCard(entity.getCertCode());
            entity.setCustName(DataMaskUtil.chineseName(entity.getCustName()));
        });
        return entities;
        }
        LambdaQueryWrapper<CreditquotaEntity> warp = new LambdaQueryWrapper<>():
        warp.apply("
zoneno = {0}","1702");
        List<CreditquotaEntity> list = creditquotaService.list(warp);
        String organld = sessionUtils.getCurrentUserOrganild(;
  • 查询条件拼接
QueryWrapper<CzDetail> warp = new QueryWrapper<>();
    warp.select("count(1) as count,sum(t.pay_amt) as sumPay ");
    warp.eq("view id",viewld).eq("isvalid","O").eq("isupload" "1");
    Map<String, Object> map = czDetailService.getMap(warp);
2、字符串前面补0
public static String fillZeroBeforeString(String str,int length){
        return String.format("%" +length+"s", str).replace(" ","O");
}
3、文件下载
public File downloadReport(ReqReportStaticVO reportStatic) throws 1OException {
    //定义临时文件File targetFile = File.createTempFile(UUIDUtil.getUUID0, ".xlsx");
    OutputStream fileOutputStream = new FileOutputStream(targetFile);
    List<ResReportStaticVO> staticVOS = queryReportStatic(reportStatic);
    //文件写入
    EasyExcel.write(fileOutputstream,ResReportStaticVO.class).sheet("报表统i计").doWrite(staticVOs);
    return targetFile;
}
4、普通下载方法
@ResponseBody@RequestMapping("/downLoad")
pubLic ResponseEntity<InputStreamResource> download(@RequestParam String viewId) {
    try{
        Trx0verview trxOverview=trx0verviewService.getById(viewId);
        //eap批次号
        String busiId=trxoverview.getDzzmFile();
        if(stringUtils.isNotBlank(busiId)){
            String rootPath=eapProperties.getWlorkBasePath()+"download/"+File.separator+busild+File.separator;
            Path downloadPath=Paths.get(rootPath);
            Files.createDirectories(downloadPath);

            eapService.download(busiId,downloadPath.toString());
            FiLe zip=ZipUtil.zip(rootPath,Chanset.forName("UTF-8"));
            //下载文件return ControllerUtils.responseFile(zip,"电子登记证明.zip",ControllerUtils.ENCDING DEFAULT);
        }eLse{
            throw new ICBCException("99","批次号为空");
        }
        }catch(Exception e){
            Log.error("下载文件出错!",e);
            throw newICBCException("99","电子证明下载异常!");
        }
}
5、文件导入
@Transactional(rolLbackFor = Exception.class)public void importFile(@RequestParam("file") MultipartFile file, @RequestParam("fileType") String fileType) throws I0Exception {
    //先清空摸型数据this.remove(null);
    //导入摸型数据
    EasyExcel.read(file.getInputStream(),Creditinfov0.class,new FileListener(this)).sheet()
// .headRowNumber(2)//从第几行开始
        .doRead();
    //第二种方式不用写监听器,同步
    List<NsrsxygDTo> nsrsxygs = EasyExcel.read(file.getInputStceam()).head(NsrsxygDTo.class).sheet().doReadsync();

//实体类如下:public class NscsxygDT0 {
    //从第几列取值@ExcelProperty(index = 0)private String dksgid;

    @ExcelProperty(index = 1)private String sxygbz;

    @ExceLProperty(index = 2)private String sxygrg;

    @ExceLProperty(index = 3)private String nsrmc;

    @ExcelProperty(index = 4)private String fddbrxm;
//fiLeType传值如下
<un-form-item Label=" " prop="upload">
    <un-upLoad
    cLass="upLoad-demo"
    :action="upLoad_url"
    :headers="headers"
    :accept="accept"
    :before-upLoad="handLeBeforeUpload"
    :on-success="handleSuccess"
    :on-error="handLeError"
    :fiLe-list="fileList"
    :data="{'fileType': query.fileType}"
    :show-file-list="false">
      <un-button style-"height:30px;background-coLor:mediunseagreen" size="medium" type-"primary">文件上传</un-button>
    </un-upLoad>
</un-form-item>
6、求两个string日期中间的时间
/**
     * 两个日期中间的日期集合
     * @param dateS
     * @param dateE
     * @return
     */
public static List<String> betweenDays(String dateS,String dateE){
        LocalDate begin = LocalDate.parse(dateS, DateTimeFormatter.ofPattern("yyyyMMdd"));
        LocalDate end = LocalDate.parse(dateE, DateTimeFormatter.ofPattern("yyyyMMdd"));
        while (begin.compareTo(end) <= 0){
            //中间的天数Period between = Period.between(begin, end);
            System.out.println(between.getDays());
            begin = begin.plusDays(1);
        }
        return list;
    }
7、对象拷贝
BeanUtils.copyProperties(commFields,fileDTO);
8、生成uuid
public static void main(String[] args) {
        String uuid = UUID.randomUUID().toString().replace("-", "");
        System.out.println(uuid);
    }
9、实体类日期格式处理
@DateTimeFormat(pattern ="yyyy-MM-dd HH:mm:ss")//定义前端(入参)数据格式@JsonFormat(timezone ="GMT+8",pattern = "yyyy-MM-dd HH:mm:ss")//json时间格式private Date operTime;
10、文件打成zip
ZipUtil.zip(path);
11、判断字符串最后一个字符
String ftpPath = vo.getFtpPath();
    if(!ftpPath.endsWith("/")){
        ftpPath = ftpPath + "/";
    }
12、list互转json、string
//list转json、stringString test = JS0N.toJS0NString(commonFields.getAgent_list());
    //string转jsonGson gson = new Gson();
    JsonArray verArray = gson.fromJson(verList, JsonArray.class);
13、实体类或者任何对象空值不返回注解和忽略注解
//JsonInclude.Include.NON_NULL 当前字段不空的时候返回字段才输出否则响应报文不展示@JsonInclude(JsonInclude.Include.NON_NULL)public String receiptNo;//回执号//JsonIgnore表示该字段不会出现在响应报文中@JsonIgnoreprivate Long viewId;
14、mybatisplus后台向前端传输long精度丢失问题
//在字段上加入如下注解即可@JsonSerialize(using = ToStringSerializer.class)private Long id;
15、数组自动排序
TreeSet<Object> treeSet = new TreeSet<>();
    treeSet.add("O.0.8");
    treeSet.add("0.0.3");
    treeset,add("0.0.7");
    Log.info("自动排序列表列表:"+treeSet.toString());
    -- [0.0.3, 0.0.7,0.0.8]
16、mybatis的@Select()注解用法
@Select()里面的>和<=需要转义>=
@SeLect("<script>"+
    " select p.*,e.card.type,e.username,e.phoneno,e.car.License,d.pay_count,d,status,d,update.time,d.ret msg,e." from (select t.*from (select * from loc-etcjzk.2aymentdetail his union all select * from Loc etcjzk-2ayme"" +
        "<if test='params.startDate != null'>"+
            "and t.PAYMENTDATE &gt;= to_date (#{params.startDate}, 'yyyy-mm-dd') "+
        "</if>"+
    "<if test='params.endDate != null'>" +
        "and t.PAYMENTDATE &lt; to_date (#{params.endDate},'yyyy-mm-dd') + 1 "+
    "</if>"+
    "<if test='params.status == 2'>""and t.TWICEPAYMENTFLAG=1 "+
    "</if>"+
    "<if test='params.status == 0'>"+"and t.TWICEPAYMENTFLAG=0 "+
    "</if>"+
    "<if test='params.status != null '>" 
        "and t.PAYMENTRESULI=#{panams.status} "
    </if>"+
    "<if test='params.bankcardng != nuLt'>"+
        "and t.ONCEPAYMENTBANKCARDNO=#(params.bankcardno} "."</if>""<if test='params.etccacdng t= nuLL'>""and t.ETcCARDNo=#{params.etccardng} ) p "+
    <if>
        "Left join loc-etcizk-pay_advance d on p.id = d.pay_detail_id left join loc.etcizk_sign e on p.etccardng ="cif test='params.cardType != null'>"+"where e.CARD_TYPE = #params.cardType} "+"order by p.PAYMENTDATE "+"</script>")
    List<Map> queryPaymentDetailList(@Param("params") Hap<String, String> params);

public List<String> getXydmByAcc(String acconut) {
    return baseMapper.getXydmByAcc(acconut);
}

import io.Lettuce.core.dynamic.annotation.Param;
@Select("select m.xyan from Loc-czzhik-zhxx t left join loc-czzhik.xxdmn m on t.ysdwbh=m.dwom where t-acconut- #lecconut) ")
List<String> getXydmByAcc(@Param("acconut") String acconut);
17、mybatis更新null不生效
实体中传入空字段将更新为nUlL,加入如下注解
/**
 *代理种类
 * /
@TableField(updateStrategy = FieldStrategy.IGNORED)
private String agentType;
18、判断异常是否属于ICBCException
if(e instanceof ICBCException){
        throw new ICBCException(ICBCException) e).getcode(),(ICBCException) e).getMsg());
    }
19、mybatisplus-distinct用法
public List<Object> payNoList(String viewId){
    QueryWrapper<CzDetail> warp=new QueryiWrappers>();
    warp.select("distinct pay_no ").lambda().eo(CzDetail::getViewId,viewId);
    return this.listObjs(warp);
}
20、EasyExcel自定义模板填充下载
//文件excel模板(其中。表示list的意思,不带.这表示单条)
公务卡还款账户 支付编号(20位) 序号 金额 还款标注
{.accountNo} {.payNo} {.serialno} {.account} {.hkbz}

    //Java代码如下/* 核对失败清单下载
         * @param acclet点
         *@return
         */public File getFailList(List<AccountDetail> accDets) throws IOException {
        //读取模板文件(resources下建立file文件夹)File tempFile = new ClassPathResource("file/check-fail-list.xlsx").getFile();
        //导出的文件名称File targetFile = File.createTempFile(GwkUtils.getUuID(),".xlsx");
        //数据
        List<Map> fillData = new ArrayList<>();
        for (AccountDetail accDet:accDets) {
            HashMap<Object, Object> map = new HashHapc>();
            map.put ("accountNo",accDet.getAccountNo());//内部户
            map.put("payNo",accDet.getPayNo());//支付编号
            map.put("seriaLno",accDet.getSerialno());//序号
            map.put("account,accDet.getZhAnount());//金额
            map.put ("
hkbz",accDet.getCheckMsg());//还款标注
            fillData.add(map);
        }
        //文件导出
        EasyExceL.write(targetFile.getPath()),withTempLate(tempFile.getPath()),sheet().doFill(fil1Data)
        retunn targetFile;
    }
21、mybatisplus-and()or()用法
List<AccountDetail> accountDetailList = accountDetailService.List(
            new LambdaQueryWrapper<AccountDetail>().eq(AccountDetail::getViewId, ViewId).eg(AccountDetail::getNocheck,"O")
        .and(warp->warp.ne(AccountDetail::getCheckRet,"0").or(),isNull(AccountDetail::getCheckRet))
    };
22、下拉框列表查询
<un-form-item Label="类型标识" prop="roLes">
      <un-select v-model="query.typeFLag" clearable pLaceholder="请选择" styLe="width:100%">
        <un-option v-for="item in type_fLag" 
                   :key="item.typeFLag"
                   :Label="item.typeFLag"
                   :value="item.typeFLag">
        </un-option>
      </un-select>
    </un-form-item>
    //下拉选择-类型标识
    type_fLag:[],

    mounted() {
        //下拉框初始化
        this.queryTypeFLag();
    }

//类型标识下拉框
    queryTypeFLag(){
      axios.get(this.uri_type_fLag).then(response => {
      // console.Log(response.data.code==1)
      this.type_fLag = response.data.data;
      if(response.data.code==1){
        this.$notify.error({
        title:"警告",
        type:"warning",
        message:response.data.msg,
      });
      return;
      }
    }).catch(e => {
      consoLe.Log('error:'+ e);
    })
    }
@RequestMapping("/typeFLags")public String selectTypeFlags(){
        List<Params> typeFLags=paramsService.selectTypeFlags();
        if(typeFLags.size()<=0){
        throw new ICBCException("99","类型标识下拉框查询异常");
        }
        HnResponseEntity entity=HnResponseEntity.getInstance("0","类型标识下拉框查询成功",typeFlags);
        return entity.toJson()
    }
    public List<Params> selectTypeFLags() {
        QueryWrappercParams warp = new QueryWrapper<();
        warp.select(" distinct type.flag ");
        retumn this.List(warp);
    }
23、mybatisplus、paas云日志Sql不打印问题
yml中加入如下内容即可:mybatis-plus:configuration:Log-impl: org.apache.ibatis.logging.stdout.StdOutImpL
24、判断对象或者字符串是否为nuLl
String str= "777888部户-sq-4124250-4100225115汇入666552154545451";
    String zfbh = sz0rhg(str);
    if(!0bjects.isNull(zfbh) && zfbh.startsWith("-")){
        fzfbh = zfbh.substring(1);
    }
    System.out.println(zfbh);
点击上方蓝色文字关注↑↑↑↑↑
转发,点赞,在看,安排一下?

最新文章

随机文章