Java开发常用小功能干货分享
个人开发时记录的一些笔记分享
1.项目启动
jar包启动:
方式一:进程停止,服务停止
java -jar 'jar包名'
方式二:服务一直运行
nohup java -jar /home/jgt/jgt-admin.jar > /dev/null 2> /dev/null &
查看占用进程
netstat -ano | findstr :31902
taskkill -pid 36736 -f
2.错误码
400 (错误请求) 请求要求必须的参数,及参数类型
401 (未授权) 请求要求身份验证。 对于需要登录的网页,服务器可能返回此响应
403 (禁止) 服务器拒绝请求
404 (未找到) 服务器找不到请求的网页
405 (方法禁用) 禁用请求中指定的方法,检查请求方式(get/post)
500 (服务器内部错误)
501 (服务器无法识别请求方法)
502 (Bad Gateway错误)
503 (服务器目前无法使用)
504 (无法请求网关)
505 (服务器不支持请求中所用的 HTTP 协议版本)
3.JSON互转
对象转json:String json = JSON.toJSONString(student);
jsonStr转对象:Student student = JSON.parseObject(jsonStr,Student.class);
String转JSONObject:JSONObject jsonObj = JSON.parseObject(str);
JSONObject转String:String str = JSON.toJSONString(jsonObj);
JSONObject转对象:Student student = JSONObject.toJavaObject(jsonObj, Student.class);
JSONArray转对象list:List<Student> studentList = JSONArray.parseArray(jsonArrayStr, Student.class);
list转JSONArray:JSONArray jsonArray = JSONArray.parseArray(JSON.toJSONString(studentList));
map转对象:User user = JSON.parseObject(JSON.toJSONString(obj), User.class);
mapList转对象list:List<User> userList = JSON.parseArray(JSON.toJSONString(mapList), User.class);
4.mysql
docker exec -it mysql bash # 进入mysql容器
mysql -u root -p # 登录mysql
show variables like 'max_connections'; # 查看最大连接数
set global max_connections=2000; # 修改最大连接数
flush privileges; # 刷新权限
show variables like 'max_connections'; # 查看最大连接数
mysql查询编写顺序:
select
from
join on
where
group by
having
order by
limit
mysql查询执行顺序:
from
on
join
where
group by
having
select
distinct
order by
limit
查询判断:case when 条件 then 结果1(条件成立) else 结果2
查询分组排序:row_number() over(),执行晚于 where 、group by
row_number() over(partition by 分组列 order by 排序列 desc)
group by 和 order by 同时使用:
order by 必须包含在 group by 中
子查询 order by 后加上 limit
字段拼接:update bz_order set store_name = CONCAT('1',store_name)
还原字段默认值
update member set member_nick_name = DEFAULT(member_nick_name), member_true_name = DEFAULT(member_true_name) where member_mobile = '18559659316';
查询表中重复数据:
SELECT
parking_name
FROM
property_parking_fee
WHERE
apartment_name = '南洋水岸'
GROUP BY
parking_name
HAVING
count( parking_name )> 1;
删除表中重复数据:
DELETE
FROM
property_parking_fee
WHERE
parking_fee_id NOT IN ( SELECT parking_fee_id FROM ( SELECT min( parking_fee_id ) AS parking_fee_id FROM property_parking_fee WHERE apartment_name = '南洋水岸' GROUP BY parking_name ) A );
多个条件中选择一个的单条件查询
choose-when-ortherwise,相当于switch-case-default
<select id="selByCondition2" resultMap="rm">
select *
from mybatis where
<choose>
<when test="status !=null">
STATUS=#{STATUS}
</when>
<when test="companyName !=null and companyName !=''">
company_name like #{companyName}
</when>
<when test="bracdName !=null and bracdName !=''">
bracd_name like #{bracdName}
</when>
<otherwise>1=1</otherwise>
</choose>
</select
5.mongodb
查询集合中重复数据(查询字段deviceId在集合sr_metadata_event_log中是否存在重复数据)
db.getCollection("sr_metadata_event_log").aggregate([
{$group:{_id:'$deviceId',count:{$sum:1}}},
{$match:{count:{$gt:1}}}
],{allowDiskUse:true})
6.list互转
list转String:StringUtils.join(list,',')
逗号隔开String转list:List<String> list = Arrays.asList(url.split(","));
List<ProductVO> productList = page.getRecords().stream().map(record -> BeanUtil.copyProperties(record, ProductVO.class);
}).collect(Collectors.toList());
list整形字段求和:list.stream().mapToInt(E::getValue()).sum()
list金额字段求和:list.stream().map(E::getValue()).reduce(BigDecimal.ZERO, BigDecimal::add);
对象list转idList:List<Long> storeIdList = vendors.stream().map(Vendor::getStoreId).collect(Collectors.toList());
统计集合中符合条件的数据数量:long count = list.stream().filter(s -> s.getId() == 1).count();
统计集合中符合条件的数据:List<Demo> demoList = list.stream().filter(s -> s.getNum() == 2).collect(Collectors.toList());
两个list去重:List<String> collect = Stream.of(list, list1).flatMap(Collection::stream).distinct().collect(Collectors.toList());
list字段排序:List<OrderProduct> orderProductList = orderProductList.stream().sorted(Comparator.comparing(OrderProduct::getOrderSn)).collect(Collectors.toList());
list过滤后排序再取值:List<String> orderProductList = orderProductList.stream().filter(orderProduct -> orderProduct.getProductNum().equals(20))
.sorted(Comparator.comparing(OrderProduct::getOrderSn).reversed()).map(OrderProduct::getOrderSn).collect(Collectors.toList());
list分组:Map<Long, List<Cart>> mapByOne = storeCartList.stream().collect(Collectors.groupingBy(Cart::getBranchStoreId));
将学生成绩为空的同学记上0分返回:List<Student> peekStudents = students.stream().filter(student -> student.getScore() == null).peek(student -> student.setScore(0))
.collect(Collectors.toList());
list删除:list.removeIf(item -> item.getBranchStoreId().equals(storeCartGroup.getBranchStoreId()));
list去掉前2个元素:List<User>> list = userList.stream().skip(2).collect(Collectors.toList());
list获取前2个元素:List<User>> list = userList.stream().limit(2).collect(Collectors.toList());
int类型转Long:List<Long> list = userList.stream().mapToLong(User::getAge).boxed().collect(Collectors.toList());
正向按中文排序:List<String> collatorNames = names.stream().sorted(Collator.getInstance(Locale.CHINA)).collect(Collectors.toList());
反向按中文排序:List<String> reverseOrderNames = names.stream().sorted(Collections.reverseOrder(Collator.getInstance(Locale.CHINA))).collect(Collectors.toList());
按照年龄进行排序,年龄相同则通过id进行排序:List<Student> collectStudents = students.stream().sorted(Comparator.comparing(Student::getAge).thenComparing(Student::getId))
.collect(Collectors.toList());
strings中是否有包含的元素:boolean anyMatchBcStrings = strings.stream().anyMatch(s -> s.contains("bc"));
检查集合中的元素是否都大于0:boolean result = strings.stream().allMatch(s -> s>0);
检查集合中的元素长度是否都不大于5:boolean result = strings.stream().noneMatch(s -> s.length()<5);
Iterator迭代器:Iterator<Integer> iterator = list.iterator();
while (iterator.hasNext()) {
Integer next = iterator.next();
iterator.remove();
}
entrySet()迭代:Set<Map.Entry<String, String>> entries = map.entrySet();
for (Map.Entry<String, String>entry:entries){
String value = entry.getValue();
String key = entry.getKey();
}
7.idea
修改git提交用户名
git config user.name
git config --global user.name "hedrick"
git config user.name
修改文件头
editor -- file and code templates
设置背景图
appearance -- UI options
或 双击shift:Set BackGround Image
常用插件
adapter for eclipse code formatter
Alibaba Cloud Toolkit
Alibaba Java Coding Guidelines
camelCase
Checkstyle
CodeGlance
Free MyBatis Tool
generateAllSetter
google-java-format
MyBatis Log Free
MyBatisCodeHelperPro
MybatisX
RestfulTool
Translation
8.日期
java日期转换
ISO8601格式,需引入hutool依赖
2023-12-12T14:47:53+08:00 转换成 "yyyy-MM-dd HH:mm:ss"
Date date = DateUtil.parse(utcString); //String类型 先转换为date类型
SimpleDateFormat s = new SimpleDateFormat(format); //格式化
s.format(date);
获取本月最后一天
LocalDate localDate = LocalDate.of(queryYear, queryMonth, 1);
int lastDayOfMonth = localDate.lengthOfMonth();
Date转LocalDateTime:
Date date = new Date();
// 方法一
LocalDateTime localDateTime = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
// 方法二
return LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault());
LocalDateTime转Date:
LocalDateTime localDateTime = LocalDateTime.now();
Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
字符串转LocalDateTime:
LocalDateTime.parse(dateStr, DateTimeFormatter.ofPattern(pattern));
LocalDateTime转字符串:
localDateTime.format(DateTimeFormatter.ofPattern(pattern);
9.其他
map存入相同key:IdentityHashMap<String,String> map = new IdentityHashMap();
map.put(new String("k1"),"A");
map.put(new String("k1"),"B");
System.out.println(map);
循环依赖:SpringContextUtil.getBean(CountryService.class).findOneById();
四舍五入(向下取整):BigDecimal.ROUND_HALF_UP
向上取:BigDecimal.ROUND_UP
向下取:BigDecimal.ROUND_DOWN
10.未完待续