2021-07-11

@JsonFormat:后端返回数据给前端,将Date类型转换为String @JsonFormat(pattern=“yyyy-MM-dd HH:mm:ss”, timezone=“GMT+8”) 返回给前端的为东八区的时间
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = “yyyy-MM-dd HH:mm:ss”, timezone = “GMT+8”)可以代替下面的注解
@DateTimeFormat:前端传递Date样式的数据到后端,后端可以通过转换来使用Long或者Date接收

@Enumerated(EnumType.ORDINAL)用在数据库的实体类中,给属性为枚举类型,但是数据库中存储为对应的下标值

@Transient:用在数据库实体类中,只是查询时改属性不参与

@JsonSerialize(using = ToStringSerializer.class):用在返回给前端的实体类上,该属性的类型一般为Long类型

@EqualsAndHashCode(exclude = {“alarmHistorySet”})

@JsonIgnore:后端返回给前端的属性不想被传递时使用

@JsonInclude(JsonInclude.Include.NON_NULL)用来去除数据中的空值

map.computeIfAbsent(“key”, k -> new Object());

cloudUserList.sort(Comparator.comparing(BillingJobHandler::apply));

List aliusers = resultBean.getObject(“aliAccounts”, new TypeReference<List>(){})

List subList = list.subList(i * len, ((i + 1) * len > size ? size : len * (i + 1)));

Map<String, Double> billItemRespMap = billItemRespList.stream().collect(Collectors.groupingBy(o -> DateFormatUtils.format(o.getConsumeDate(), “yyyy-MM-dd”), Collectors.summingDouble(BillItemResp::getAmount)));

String m = DurationFormatUtils.formatPeriod(instance.getTime().getTime(), new Date().getTime(), “M”);

Calendar instance = Calendar.getInstance();

int maximum = instance.getActualMaximum(Calendar.DAY_OF_MONTH);

private static NumberFormat format = NumberFormat.getInstance();

Stream.concat(groupuserStream, userSteam).distinct().collect(Collectors.toList());

noticeUsers.stream().map(userId -> userMap.get(userId)).filter(Objects::nonNull);

items.stream().anyMatch(o -> (o.getSubscribeType().indexOf(“BillingItemDetail”) > -1 && o.getSubscribeBucket().equals(cloudUser.getObsBucketName())));

@Cacheable(cacheNames = CacheConstant.CONFIGURATION_TEMPLATE_CACHE, key = " #root.methodName + #root.args[0]")

SearchHit hit = topHits.getHits().getAt(0);
Map<String, Object> map = hit.getSourceAsMap();

Strings.EMPTY_ARRAY

MapUtils.getString

ReflectionUtils.makeAccessible(field);

SortOrder.fromString(queryCondition.getOrder()); es中的排序

es在模糊查询时:
String[] fbsArr = { “\”, “$”, “(”, “)”, “", “+”, “.”, “[”, “]”, “?”, “^”, “{”, “}”, “|” };
return (x, y) -> {
String s = y.toString();
for (String key : fbsArr) {
if (s.contains(key)) {
s = s.replace(key, “\” + key);
}
}
QueryBuilder queryBuilder = QueryBuilders.wildcardQuery(x, ("
” + s + “*”).toLowerCase().trim());

jpa在模糊查询时:
x.like(z.get(n),’%’+escape(y.toString())+’%’,’/’);
StringUtils.isEmpty(text) ? text : text.replaceAll("/", “//”).replaceAll("", "/").replaceAll("%", “/%”);

@JSONField(name = “globalSubordinateTenant”,serializeUsing = ToStringSerializer.class)在json序列化时可更改属性名

XXL-JOB手动执行任务:
public JobResult trigger(String id, Object param) {
ReturnT result = XxlJobRemotingUtil.postBody(String.format("%sjobinfo/%s/trigger", this.addressUrl, id), this.accessToken, param, 3);
return JobResult.builder().code(result.getCode()).msg(result.getMsg()).content(result.getContent()).build();
}

分片执行:
	ShardingUtil.ShardingVO shardingVO = ShardingUtil.getShardingVo();
    int index=shardingVO.getIndex();

JSONArray parseArray = JSONObject.parseArray(body);
JSONObject jsonData = JSONObject.parseObject(object.toString());

@RequestPart

ReadContext ctx = JsonPath.parse(json);
List authors = JsonPath.read(json, “$.store.book[*].author”);
HashMap<String, List<?>> read1 = JsonPath.parse(json).json();

EntityUtils.toString(response.getEntity(),“UTF-8”) //将请求的流转换为字符串
EntityUtils.consumeQuietly(response.getEntity()); //关闭流

建立SSL连接的方式:https://www.cnblogs.com/unknows/p/8534713.html

dao.findAllById(list) jpa

jpa三元表达式:if(?3 is not null,r.account_id = ?3,1=1)
Arrays.asList(projectId)

@ConfigurationProperties(prefix = “configuration.attribute”, ignoreUnknownFields = false)

Map<String, Object> param = Collections.singletonMap(isProject ? “project_name” : “org_name”, name);

JSONUtil.toJsonStr(resourceJson)

监听器:
@Autowired
private ApplicationEventPublisher eventPublisher;
@EventListener

String secretKey = RandomStringUtils.randomAlphanumeric(32);
ResponseEntity.ok().headers(headers).body(data);

sorted(Comparator.comparing(UserContactResp::getName, Collator.getInstance(Locale.CHINA)))

FileCopyUtils.copy(obsObject.getObjectContent(), response.getOutputStream());

@ApiModelProperty(“告警通知方式”)
private Budget.NoticeWay[] noticeWays;

BigDecimal.ZERO

TreeSet treeSet2 = dishList.stream()
.collect(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(Dish::getId))));

测试Collectors.collectingAndThen方法:将流中的数据通过Collector计算,计算的结果再通过Function处理一下(这里是将TreeSet转为ArrayList。即相当于将最终结果又经过了new ArrayList<>(treeSet))
List newDishList = dishList.stream().collect(Collectors.collectingAndThen(
Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(Dish::getId))), ArrayList::new));

BudgetItem.Status status = BudgetItem.Status.valueOf(item);
return status.ordinal();

Date date = new Date(1608535687702L);

LocalDate now = LocalDate.now();
LocalDate timeScopeLocal = Instant.ofEpochMilli(item.getTimeScope()).atZone(ZoneOffset.ofHours(8)).toLocalDate();

BigDecimal.valueOf(years).add(monthToYear);
long between = ChronoUnit.HOURS.between(now2, now1);//计算两个日期之间的差值

lists.stream().flatMap(list -> list.stream())

StringUtils.join(ids, ‘,’)
LocalDate now
now.atStartOfDay(ZoneId.systemDefault()).toInstant().toEpochMilli()

LocalDateTime now = LocalDateTime.now();
ZonedDateTime zonedDateTime = now.atOffset(ZoneOffset.ofHours(4)).toZonedDateTime();
System.out.println(zonedDateTime);
LocalDateTime localDateTime = zonedDateTime.toInstant().atOffset(ZoneOffset.ofHours(8)).toLocalDateTime();
System.out.println(localDateTime)

extends JsonSerializer

Base64.getEncoder().encodeToString()

NumberUtils

BASE64Decoder base64Decoder = new BASE64Decoder();
base64Decoder.decodeBuffer()

String finalProduct_type = MapUtils.getString(map, “product_name”, “–”); package org.apache.commons.collections4;

ByteArrayResource contentsAsResource = new ByteArrayResource(byteArrayOutputStream.toByteArray()) {
@Override
public java.lang.String getFilename() {
return “ttttttt.pdf”;
}
};
MultiValueMap<String, Object> objectObjectLinkedMultiValueMap = new LinkedMultiValueMap<>();

RandomUtil.randomString(5)

HttpHost[] httpHosts = Arrays.stream(split).map(this::makeHttpHost).filter(Objects::nonNull).toArray(HttpHost[]::new);

switch(这里可以是个枚举)

Objects.requireNonNull(“sdf”) //如果为null直接报空指针异常

File file = new File(filePath);
file.deleteOnExit(); //程序退出时删除文件

@Component
@Order(value = 1)//可以通过order来控制顺序
public class PushMessageService implements ApplicationRunner {
run(){}
}

headers.setContentType(MediaType.APPLICATION_JSON);

orderDefResponses.parallelStream().map(OrderDefResponse::getErrorNum).min(Integer::compareTo).get();

Collections.shuffle(resolvedAddresses)

ArrayList objects = Lists.newArrayList();
objects.removeIf()

assert StringUtils.isNotBlank(""):“天天向上”;
assertEquals()
Assert.assertEquals();

String collect = map.keySet().stream().map(key -> {
return key + “=” + map.get(key);
}).collect(Collectors.joining("&", “?”, “”));

try {
Person forObject = restTemplate.getForObject(“http://localhost:8402/test/test?tt=84”, Person.class);
System.out.println(forObject);
} catch (RestClientResponseException e) {//被调用的服务服务背部出现异常走这个
int rawStatusCode = e.getRawStatusCode();
log.error(“call remote resp exception”, e);
responseEntity = new ResponseEntity(HttpStatus.valueOf(rawStatusCode));
System.out.println(e.getResponseBodyAsString());//可以获取异常的详细信息
}catch (ResourceAccessException e){//被访问的服务无法连接异常
log.error(“ResourceAccessException:{}”,e.getCause());
}catch (Exception e){//请求或响应的参数异常
log.error(“sssssssException:{}”,e.getCause());
}

jpa中关于in的sql查询,如果需要判断in里的值是否为null,需要使用List类型,并且需要使用coalesce函数:if(coalesce (?4) is not null,t.project_id in (?4),1=1)

Optional user1 = Optional.ofNullable(user);
user1.ifPresent(s->{
System.out.println(s.getName());
});

	user1.ifPresent(s->{})

list1.retainAll(list2)

Permission.Visible.values()[AppContext.currentTenantType()]//【】中是序号

coalesce (?4) sql语句

headers.add(HttpHeaders.CONTENT_DISPOSITION, “attachment;filename*=UTF-8’’” + filename);

ublic static final String UTF_8 = StandardCharsets.UTF_8.name();

StopWatch stopWatch = new StopWatch();
stopWatch.start();
stopWatch.stop();
stopWatch.prettyPrint();

避免事务失效的方案:
方法A调用方法B,B上事务注解,如果不想让B上的事务失效,可以通过 applicationContextUtil.getBean(FileService.class)来获取该类对象,通过这个对象去调用B方法

@NotFound(action= NotFoundAction.IGNORE)意思是找不到引用的外键数据时忽略,

Timestamp.from(Instant.now())

RandomAccessFile:分段上传文件神器

可以在接口中定义map,可以在他的实现中共享

int insert = fileShardRecordDao.saveRecord(fileShardUploadRecord);
if(insert == 0){
log.info("当前发生同一客户:{}, 上传同一文件:{} ",fileShardUploadRecord.getUserId(),fileShardUploadRecord.getMd5());
throw AppException.of(FileCode.SHARD_FILE_UPLOADING);
}

FileUtils.copyInputStreamToFile(fileShardUploadRequest.getFile().getInputStream(), tempFile)

TokenFilter extends OncePerRequestFilter

PathMatcher pathMatcher = new AntPathMatcher();
pathMatcher.match(item.trim(), request.getRequestURI())//进行路径匹配

MessageFormat

Arrays.toString()

DateUtils日期操作工具类

FileSystemUtils.deleteRecursively
PriorityQueue pq = new PriorityQueue<>();//要通过迭代器的方式去取值,这样才是有顺序的

restTemplate.getForObject(url, JSONArray.class, parameter);//可以解析为JSONArray但是不能直接解析为List

@FeignClient(name = “anHengOrderApi”,url = “ a n h e n g . o p e n a p i . b a s e . u r l " , p a t h = " {anheng.openapi.base.url}",path = " anheng.openapi.base.url",path="{anheng.openapi.base.path}”,configuration = AnHengApiErrMsgConfiguration.class)

Student json = JsonPath.parse(JSONObject.toJSONString(map1)).read("$.aaa",Student.class);

private static final DateTimeFormatter shotDate = DateTimeFormatter.ofLocalizedDate(FormatStyle.SHORT);

JSONArray jsonArray = JSONArray.parseArray(entity.getBody());
List ts = jsonArray.toJavaList(ProjectInfo.class);

AtomicBoolean building = new AtomicBoolean();
boolean b = building.compareAndSet(false, true);

jsonObjects.stream()
.filter(s -> Objects.nonNull(s.getString(OrderConstant.SecurityService.PRICE)))
.collect(Collectors.groupingBy(s -> s.getString(OrderConstant.SecurityService.CODE),
Collectors.mapping(s -> new BigDecimal(s.getString(OrderConstant.SecurityService.PRICE)),
Collectors.reducing(BigDecimal.ZERO, BigDecimal::add))));

IntStream.range(0,ldapDnConfigList.size()).forEach

sql语句:update_time = now()

分页算法:int totalPageNum = (totalRecord + pageSize - 1) / pageSize;

List<List> segmentList = IntStream.range(0, (subList.x() + pageSize - 1) / pageSize)
.map(pageNum -> pageNum * pageSize)
.parallel()
.mapToObj(i -> subList.stream().skip(i).limit(pageSize).collect(Collectors.toList()))
.collect(Collectors.toList());

having 是在groupby 后执行

ConstraintValidator 自定义校验注解

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值