常用随笔记录

145 阅读3分钟

List 是否为null

主要还是 stream 的使用

boolean isEmpty = marketIds.stream().allMatch(Objects::isNull);
List<Integer> marketIds = sysUserService.getMarketIdsByUserId(userId); 
boolean isEmpty = marketIds.stream().allMatch(Objects::isNull); 
if (isEmpty) { 
    System.out.println("marketIds is effectively empty."); 
} else { 
    System.out.println("marketIds contains non-null elements."); 
}
服务层
public int getUnreadMessages() {
    SysCrmNotice sysCrmNotice = new SysCrmNotice();
    Long userId = SecurityUtils.getUserId();
    if (!SecurityUtils.isAdmin(userId)) {//判断是否为超级管理员
        sysCrmNotice.setUserId(userId);
        List<Integer> marketIds = sysUserService.getMarketIdsByUserId(userId);//获取当前用户下所有的零工市场
        boolean isEmpty = marketIds.stream().allMatch(Objects::isNull);
        if (!isEmpty) {
            sysCrmNotice.setMarketIdList(marketIds);
        }
    }
    return sysCrmNoticeMapper.getUnreadMessages(sysCrmNotice);
}

mapper:
<select id="getUnreadMessages" parameterType="SysCrmNotice" resultType="java.lang.Integer">
    <include refid="getUnreadMessagesVo"/>
    <where>
        <if test="userId != null">
            <if test="marketIdList != null">
                and (
                (user_id = 0 and market_id in
                <foreach item="item" index="index" collection="marketIdList" open="(" separator="," close=")">
                    #{item}
                </foreach>
                )
                or user_id = #{userId}
                )
            </if>
            <if test="marketIdList == null">
                and user_id = #{userId}
            </if>
        </if>
        and status = 0
    </where>
</select>

实体类:
/** 市场ID列表 */
private List<Integer> marketIdList;

Get批量操作 传1,2,3

public int deleteSysCrmNoticeByNoticeIds(Long[] noticeIds)
{
    return sysCrmNoticeMapper.deleteSysCrmNoticeByNoticeIds(noticeIds);
}

<delete id="deleteSysCrmNoticeByNoticeIds" parameterType="String">
    delete from sys_crm_notice where notice_id in 
    <foreach item="noticeId" collection="array" open="(" separator="," close=")">
        #{noticeId}
    </foreach>
</delete>

Asserts.isNullOrEmpty 自定义验证不为空

Asserts.isNullOrEmpty(lyInterviewInvitation.getMemberId(), "memberId不能为空");

Objects.isNull 和 Objects.nonNull

isNull 方法用于检查给定的引用是否为 null。如果引用为 null,则返回 true;否则返回 false

nonNull 方法用于检查给定的引用是否不是 null。如果引用不是 null,则返回 true;否则返回 false

@DataSource 切换数据源

@DataSource(value = DataSourceType.MASTER)

@DataSource(value = DataSourceType.DASHBOARD)

日志记录

private Logger logger=LoggerFactory.getLogger(LyCustomerSignServiceImpl.class);

logger.info()
logger.error()

时间、日期

// 获取当前日期的时间戳
        Date nowDate = new Date();
        long dayTime = nowDate.getTime() / 1000; // 转换为秒级时间戳
        
        System.out.println("Current Unix timestamp in seconds: " + dayTime);

DTO等文件分别代表用在哪里

dto 请求的参数类 可以继承domain实体类,req是远程调用,resp是外部接口返回的,
vo也是用来返回的、用于后台的。

Json相关

JSONObject.parseObject() 方法将一个 JSON 字符串转换成一个 Java 对象:
LyWorkRecordPoint lyWorkRecordPoint = JSONObject.parseObject(msg, LyWorkRecordPoint.class);

Get查询,自定义查询参数

http://192.168.0.51:3400/dev-api/group/info/jobRecord?pageNum=1&pageSize=10&marketEnterId=100006&startTime=1727280000&endTime=1729958399
@ApiOperation("零工工作记录-工作记录列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "district", value = "地区", required = true, dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "startTime", value = "开始时间", required = true, dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "endTime", value = "结束时间", required = true, dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "status", value = "状态-已报名/单位已确认", required = false, dataType = "String", paramType = "query")
    })
    @Log(title = "获取零工工作记录", businessType = BusinessType.OTHER)
    @GetMapping("/jobRecord")
    public TableDataInfo jobRecordlist(@Param("status") String status,@Param("ygfName") String ygfName, @Param("startTime") Long startTime, @Param("endTime") Long endTime, @Param("enterpriseName") String enterpriseName, @Param("marketId") String marketEnterId) {
        startPage();
        List<LyJobResp> list = lyGroupService.selectLyjobRecordlist(status, startTime, endTime, enterpriseName, marketEnterId, ygfName);
        return getDataTable(list);
    }


@Select("<script> SELECT code FROM students where code in "
		+ "<foreach item='item' index='index' collection='codeList' open='(' separator=',' close=')'>"
		+ "#{item} </foreach>" + "</script>")
List<String> selectCodeByCodeList(@Param("codeList") List<String> codeList);

StringUtils 工具类

//如果字符串为 null 或者长度为0,则返回 true。否则,返回 false。
if(StringUtils.isEmpty(enterInfo.getEnterprisename())){
            String name= iLyEnterInfoService.getEnterNameByEnterId(memberId);
            if(StringUtils.isEmpty(name)){
                return;
            }else{
                enterInfo.setEnterprisename(name);
            }
        }
StringUtils.isBlank 是 Apache Commons Lang 库中的一个实用方法,用于检查一个字符串是否为空或空白。这个方法非常方便,可以用来简化对字符串的空值和空白字符的判断。

HttpUtils.sendPost

private void pushToPassSms(LyUnbindRequests lyUnbindRequests){
    // 定义请求参数
    String phone = lyUnbindRequests.getContactTel();
    String randomKey = "hiWFhJkDNC2j04eJ";
    String templateCode = "SMS_475025473";
    String options = "";
    // 构建请求参数字符串
    String param = null;
    try {
        param = String.format(
                "phone=%s&randomKey=%s&options=%s&templateCode=%s",
                URLEncoder.encode(phone, StandardCharsets.UTF_8.toString()),
                URLEncoder.encode(randomKey, StandardCharsets.UTF_8.toString()),
                URLEncoder.encode(options, StandardCharsets.UTF_8.toString()),
                URLEncoder.encode(templateCode, StandardCharsets.UTF_8.toString())
        );
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(e);
    }
    // 调用 sendPost 方法
    String smsUrl = lgbHttps+SMS_TYPE_UNBIND;
    String response = HttpUtils.sendPost(smsUrl, param, false);
    // 使用 Gson 解析 JSON 字符串
    JsonObject jsonObject = JsonParser.parseString(response).getAsJsonObject();
    // 获取 code 的值
    int code = jsonObject.get("code").getAsInt();
    log.info("通过短信通知{}", code);
}

Long类型createTime 时间戳转日期 yyyy-MM-dd HH:mm:ss

@JsonSerialize(using = TimestampSerializer.class)
private Long createTime;

自定义序列化器

package com.ruoyi.common.utils.serializer;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class TimestampSerializer extends JsonSerializer<Long> {
    private static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Override
    public void serialize(Long value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
        if (value != null) {
            Date date = new Date(value * 1000L);
            gen.writeString(dateFormat.format(date));
        } else {
            gen.writeNull();
        }
    }
}