记事本
hutool 的JSONUtil
import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) throws NoSuchFieldException {
String body = "{\"domain\":\"hwork_market\",\"queryType\":\"and\",\"roleCode\":\"ZX_CYZJ_new\",\"dimensionObjectList\":[{\"dimensionCode\":\"mkt\",\"authorityCodeList\":[\"12A02\"]},{\"dimensionCode\":\"cat\",\"authorityCodeList\":[\"CA\"]}]}";
JSON parse = JSONUtil.parse(body);
List<String> list = new ArrayList<>();
List<String> byPath = JSONUtil.getByPath(parse, "dimensionObjectList.dimensionCode", list);
System.out.println(byPath);
JSONUtil.putByPath(parse, "dimensionObjectList[0].dimensionCode", "1223");
System.out.println(parse.toString());
}
}
手动下线eureka实例(示范)
curl -X DELETE 'http://10.164.197.208:1180/eureka/apps/MMMP-SCHEDULE-SERVER/mmmp-schedule-server@10.164.204.200:9005(AutoTest.haiercash.com)'
walkFileTree
@Test
public void uploadScript() throws IOException {
String location = "D:\\data\\temp";
List<CreditCalcScript> list = new ArrayList<>();
Files.walkFileTree(Paths.get(location), new SimpleFileVisitor<Path>() {
// 处理文件
@Override
public FileVisitResult visitFile(Path path, BasicFileAttributes attrs) throws IOException {
CreditCalcScript script = new CreditCalcScript();
script.setInterfaceCode("tets");
script.setFunctionType("222");
script.setRemark("2222");
script.setStatus("Y");
String fileName = path.getFileName().toString();
script.setScriptName(fileName);
fileName = fileName.substring(0, fileName.lastIndexOf("."));
String code = fileName;
if (fileName.contains("_")) {
code = fileName.split("_")[1].toUpperCase();
}
script.setScriptCode(code);
String content = FileUtils.readFileToString(new File(path.toString()), StandardCharsets.UTF_8.name());
script.setScriptContent(content);
list.add(script);
log.debug("文件{}处理成功", path);
return FileVisitResult.CONTINUE;
}
// 处理文件出现异常
@Override
public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
log.error("文件{}处理失败", file, exc);
return FileVisitResult.CONTINUE;
}
});
creditCalcScriptService.saveBatch(list);
}
mysql查询表结构
SELECT
COLUMN_COMMENT 中文字段名称 ,
COLUMN_NAME 英文字段名称列名,
COLUMN_TYPE 数据类型,
COLUMN_DEFAULT 描述,
(
CASE
WHEN column_key != '' THEN
'是'
ELSE
'否'
END
) 是否索引,
(
CASE
WHEN column_key = 'PRI' THEN
'是'
ELSE
'否'
END
) 是否主键
FROM
INFORMATION_SCHEMA.COLUMNS
where table_name = '表名';
反射的方式配置
public void postQuery(Map<String, Object> param, List<Map<String, Object>> interfaceCodeList) {
for (Map<String, Object> interfaceCodeMap : interfaceCodeList) {
param.putAll(interfaceCodeMap);
Class<?> aClass;
try {
aClass = Class.forName("com.***.variable.***.vo.request.RequestVo");
} catch (ClassNotFoundException e) {
log.error("异常", e);
continue;
}
Object o = BeanUtil.copyProperties(param, aClass);
ReflectUtil.invoke(this, "方法名", o);
}
}
使用EasyExcel导出数据库表结构
ap<String, String> tables = new HashMap<>();
tables.put("sf_rhjk_risk_score_cr_04306", "融慧-风险分CR优享版V8.0");
tables.put("sf_white_knight_02302", "白骑士主表");
tables.put("sf_white_knight_02302_info", "白骑士主表从表");
// 表结构输出地址
String writePath = "D:\\data\\temp\\table.xlsx";
int i = 0;
ClassPathResource classPathResource = new ClassPathResource("template/template.xlsx");
ExcelWriter excelWriter = EasyExcel.write(writePath).withTemplate(classPathResource.getInputStream()).build();
for (Map.Entry<String, String> entry : tables.entrySet()) {
List<ExportTable> structure = service.getture(entry.getKey());
WriteSheet writeSheet = EasyExcel.writerSheet(i++, entry.getValue()).build();
excelWriter.fill(structure, writeSheet);
Map<String, Object> map = new HashMap<>();
map.put("tableDesc", entry.getValue());
map.put("tableName", entry.getKey());
excelWriter.fill(map, writeSheet);
}
excelWriter.finish();
}
swagger其中的一种写法
@ApiImplicitParams({
@ApiImplicitParam(value = "id主键", name = "id", dataType = "int", required = true),
@ApiImplicitParam(value = "用户id", name = "userId", dataType = "String", required = true),
@ApiImplicitParam(value = "用户名", name = "userName", dataType = "String", required = true)
})
// 导出
@ApiOperation(value = "", notes = "", produces = "application/octet-stream")
// 导入
@PostMapping("/import")
@ApiOperation("导入")
public Result import(@RequestPart(value = "file") MultipartFile file) {
return Result.ok();
}
mysql 在原值加值写法
int occupyQty = entry.getValue().stream().mapToInt(TransferVersionInfoDetail::getQty).sum();
UpdateWrapper<ProjectVersionProduct> updateWrapper = new UpdateWrapper<>();
updateWrapper.setSql("apply_qty=apply_qty-" + occupyQty);
updateWrapper.eq("project_code", transferVersionInfoNew.getProjectCode());
updateWrapper.eq("product_code", entry.getKey());
projectVersionProductService.update(updateWrapper);
json转化修改类型
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern="yyyy-MM-dd HH:mm:ss")
private LocalDateTime creTime;
update select
UPDATE st_transfer_version_info_detail z inner JOIN
(
SELECT
b.delivery_type,
a.out_locator_code,
a.in_store_code,
c.`LOCATOR_NAME`,
a.line_number
FROM
`st_transfer_version_info_detail` a
LEFT JOIN st_transfer_version_info_new b ON b.`bill_code` = a.`bill_code`
LEFT JOIN st_channel_group_locator c ON c.`LOCATOR_CODE` = a.`out_locator_code`
WHERE
b.`delivery_type` = 1
) x ON z.line_number = x.line_number
SET z.out_locator_name = x.LOCATOR_NAME
idea 常用插件
-D:spring.profiles.active=pre
MybatisPlus配置类
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import com.baomidou.mybatisplus.extension.plugins.pagination.optimize.JsqlParserCountOptimize;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* MybatisPlus配置类
*/
@Configuration
public class MybatisPlusConfig {
/**
* 分页插件
*/
@Bean
public PaginationInterceptor paginationInterceptor() {
PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
// 设置请求的页面大于最大页后操作, true调回到首页,false 继续请求 默认false
// paginationInterceptor.setOverflow(false);
// 设置最大单页限制数量,默认 500 条,-1 不受限制
paginationInterceptor.setLimit(-1);
// 开启 count 的 join 优化,只针对部分 left join
paginationInterceptor.setCountSqlParser(new JsqlParserCountOptimize(true));
return paginationInterceptor;
}
}
获取java.lang.reflect.Type
public static void main(String[] args) {
List<Person> test = test();
System.out.println(test);
}
public static List<Person> test(){
Method method = null;
try {
method = Main.class.getMethod("test");
} catch (NoSuchMethodException e) {
e.printStackTrace();
return null;
}
System.out.println(method); // 输出方法信息
Type returnType = method.getGenericReturnType();
System.out.println(returnType.getTypeName());
String s = "[{\"name\":\"zhangsan\",\"address\":\"山东青岛\"}]";
return JSONObject.parseObject(s, returnType);
}
List<Person> parm = null;
public static void main(String[] args) throws NoSuchFieldException {
Field parm1 = Main.class.getDeclaredField("parm");
Type genericType = parm1.getGenericType();
System.out.println(genericType);
}
mysql字段默认当前日期
'date_format(now(),_utf8mb3\\\'%Y-%m-%d\\\')'
QueryWrapper转换成LambdaQueryWrapper
兼顾两个优点,QueryWrapper可以直接在select写函数,LambdaQueryWrapper防止字段名编写错误
public TotalFacLedgerDTO totalAmount(FacLedgerDTO dto) {
QueryWrapper<FacLedger> queryWrapper = new QueryWrapper<>();
queryWrapper.select("sum(fac_qty) as totalFacQty, sum(un_contain_tax_qty) as totalUnContainTaxQty");
LambdaQueryWrapper<FacLedger> wrapper = queryWrapper.lambda();
wrapper.eq(StringUtils.isNotEmpty(dto.getCostDetailNo()), FacLedger::getCostDetailNo, dto.getCostDetailNo());
wrapper.eq(StringUtils.isNotEmpty(dto.getFacCode()), FacLedger::getFacCode, dto.getFacCode());
List<Map<String, Object>> maps = this.baseMapper.selectMaps(wrapper);
if (CollectionUtil.isEmpty(maps)) {
return new TotalFacLedgerDTO(BigDecimal.ZERO, BigDecimal.ZERO);
}
BigDecimal totalFacQty = Convert.toBigDecimal(maps.get(0).get("totalFacQty"), BigDecimal.ZERO);
BigDecimal totalUnContainTaxQty = Convert.toBigDecimal(maps.get(0).get("totalUnContainTaxQty"), BigDecimal.ZERO);
return new TotalFacLedgerDTO(totalFacQty, totalUnContainTaxQty);
}
apollo-config-spring-boot-starter
https://gitcode.com/izachwei/apollo-config-spring-boot-starter/tree/master/src
类属性操作
public String getName(@RequestBody Person testUser) throws NoSuchFieldException {
// 获取类属性名称
Class<Person> personClass = Person.class;
Field[] declaredFields = personClass.getDeclaredFields();
List<String> collect = Stream.of(declaredFields).map(Field::getName).collect(Collectors.toList());
System.out.println(collect);
// 获取属性值
String username = (String) ReflectUtil.getFieldValue(testUser, "username");
System.out.println(username);
// 获取属性上的注解实例
Field usernameField = personClass.getDeclaredField("username");
Test annotation = AnnotationUtils.getAnnotation(usernameField, Test.class);
System.out.println(annotation.value());
return "";
}
swagger 给注解的属性赋值
import io.github.classgraph.ClassGraph;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
@Configuration
public class DynamicSchemaConfig {
@Bean
public CommandLineRunner dynamicSchemaCustomiserRunner() {
return args -> {
for (Class<?> clazz : getClasses("com.example.demo")) {
for (Field field : clazz.getDeclaredFields()) {
Enum2AllowableValues annotation = field.getAnnotation(Enum2AllowableValues.class);
if (annotation == null) {
continue;
}
io.swagger.v3.oas.annotations.media.Schema oriSchema = field.getAnnotation(io.swagger.v3.oas.annotations.media.Schema.class);
if (oriSchema == null) {
continue;
}
String[] enumValues = getEnumValues(annotation.value(), annotation.method());
setSchemaAllowableValues(oriSchema, enumValues);
}
}
};
}
private void setSchemaAllowableValues(Object schema, String[] values) {
try {
if (Proxy.isProxyClass(schema.getClass())) {
InvocationHandler invocationHandler = Proxy.getInvocationHandler(schema);
setSchemaAllowableValues(invocationHandler, values);
return;
}
Field memberValues = schema.getClass().getDeclaredField("memberValues");
memberValues.setAccessible(true);
Map<String, Object> memberValuesMap = (Map<String, Object>) memberValues.get(schema);
memberValuesMap.put("allowableValues", values);
} catch (NoSuchFieldException | IllegalAccessException e) {
e.printStackTrace();
}
}
private String[] getEnumValues(Class<? extends Enum<?>> enumClass, String methodName) {
try {
Method method = null;
Method method2 = null;
if (methodName.indexOf(":") >= 0) {
String[] split = methodName.split(":");
method = enumClass.getMethod(split[0].trim());
method2 = enumClass.getMethod(split[1].trim());
} else {
method = enumClass.getMethod(methodName);
method2 = null;
}
final Method finalMethod = method;
final Method finalMethod2 = method2;
return Arrays.stream(enumClass.getEnumConstants())
.map(enumConstant -> {
try {
if (finalMethod2 != null) {
return finalMethod.invoke(enumConstant).toString() + ":" + finalMethod2.invoke(enumConstant).toString();
} else {
return finalMethod.invoke(enumConstant).toString();
}
} catch (Exception e) {
throw new RuntimeException(e);
}
})
.toArray(String[]::new);
} catch (NoSuchMethodException e) {
throw new IllegalArgumentException("Method " + methodName + " not found in enum " + enumClass.getName());
}
}
private List<Class<?>> getClasses(String packageName) {
// 使用 ClassGraph 库扫描包中的类
return new ClassGraph().enableAllInfo().whitelistPackages(packageName).scan()
.getAllClasses().loadClasses();
}
}
注解扫描
Set<Class<?>> classes = ClassUtil.scanPackage("com.test.boot.param",
x -> Arrays.stream(x.getDeclaredFields()).anyMatch(y -> y.isAnnotationPresent(ExcelProperty.class)));
for (Class<?> aClass : classes) {
System.out.println(aClass.getName());
}
for (Class<?> aClass : classes) {
List<Field> collect = Arrays.stream(aClass.getDeclaredFields())
.filter(x -> x.isAnnotationPresent(ExcelProperty.class)).collect(Collectors.toList());
for (Field field : collect) {
System.out.println(field.getName() + field.getAnnotation(ExcelProperty.class));
}
}
LambdaQueryWrapper做条件写法
BigDecimal sumPrice(@Param("ew") LambdaQueryWrapper<CostAllocation> wrapper);
select
sum(price)
from cost_allocation
<where>
${ew.sqlSegment}
</where>
纸上得来终觉浅,绝知此事要躬行。