1.java stream
对集合中的对象按指定字段进行分组统计并排序
>在一个list集合中的对象有相同的name,我需要把相同name的对象的total进行汇总计算,并且根据total倒序排序
/**
* 定义一个对象,这里使用了lombok的注解
*/
@Data
@Accessors(chain = true)
class Good {
private String name;
private Integer total;
}
public class Test4 {
public static void main(String[] args) {
List<Good> list = new ArrayList<>();
// 创建几个对象放在list集合中
list.add(new Good().setName("xiaomi").setTotal(2));
list.add(new Good().setName("huawei").setTotal(2));
list.add(new Good().setName("apple").setTotal(2));
list.add(new Good().setName("xiaomi").setTotal(2));
List<Good> collect1 = list.stream()
// 根据name进行分组
.collect(Collectors.groupingBy(Good::getName))
.entrySet()
.stream()
.map(entry -> {
String key = entry.getKey();
List<Good> value = entry.getValue();
Integer sum = value.stream().mapToInt(Good::getTotal).sum();
return new Good().setName(key).setTotal(sum);
})
// 根据total倒序排序
.sorted(Comparator.comparing(Good::getTotal).reversed())
.collect(Collectors.toList());
System.out.println(collect1.toString());
}
}
将对象List中的某个字段放到新的List中
List<String> ids = list.stream().map(Rq::getId).collect(Collectors.toList());
2.lombok
1.链式编程
@Accessors(chain = true)
3.mybatis(SQL)
1.查询起始到结束时间的数据
<if test="startDate != null">
<![CDATA[
AND rb.create_time >= CONCAT(#{startDate},' 00:00:00')
]]> </if>
<if test="endDate != null"> <![CDATA[
AND rb.create_time <= CONCAT(#{endDate},' 23:59:59')
]]> </if>
2.for循环
- List
<foreach item="item" collection="list" open="(" separator="," close=")">
#{item}
</foreach>
- Map<String, Object> map
map.put("ids",ids); map.put("projectId",project);
<foreach item="id" collection="ids" open="(" separator="," close=")">
#{id}
</foreach>
-
array数组
<foreach collection="array" index="index" item="item" open="(" separator="," close=")"> #{item} </foreach>
3. NOW() 用法
-
当前0点时间
select * FROM rental_tenant_record WHERE plan_end_time=DATE_FORMAT(NOW(),'%Y-%m-%d 00:00:00')
plan_end_time=DATE_FORMAT(#{toDate},'%Y-%m-%d 00:00:00')
4.时间差函数TIMESTAMPDIFF、DATEDIFF的用法
-
datediff函数,返回值是相差的天数,不能定位到小时、分钟和秒。
-- 相差2天 select datediff('2018-03-22 09:00:00', '2018-03-20 07:00:00');
-
TIMESTAMPDIFF函数,有参数设置,可以精确到天(DAY)、小时(HOUR),分钟(MINUTE)和秒(SECOND),使用起来比datediff函数更加灵活。对于比较的两个时间,时间小的放在前面,时间大的放在后面。
--相差1天 select TIMESTAMPDIFF(DAY, '2018-03-20 23:59:00', '2015-03-22 00:00:00'); --相差49小时 select TIMESTAMPDIFF(HOUR, '2018-03-20 09:00:00', '2018-03-22 10:00:00'); --相差2940分钟 select TIMESTAMPDIFF(MINUTE, '2018-03-20 09:00:00', '2018-03-22 10:00:00'); --相差176400秒 select TIMESTAMPDIFF(SECOND, '2018-03-20 09:00:00', '2018-03-22 10:00:00');
-
在存储过程中的写法:
```
注意:var_committime是前面业务中获取到需要比较的时间。
– 获取当前时间 SET var_current_time = CONCAT(CURDATE(),’ ‘,CURTIME()); – 时间比较 SET var_time_diff = TIMESTAMPDIFF(MINUTE, var_committime, var_current_time);
– 判断未审核的合同是否超过48小时未处理,如果超过则进行后续逻辑处理,否则不处理。 IF (var_time_diff > 2880) THEN
– 相关业务逻辑处理
END IF;
## 4.获取当天,当月,当年数据
SELECT r.create_time AS createTime,u.
name
,u.tel FROM place_record r LEFT JOIN place_user u on r.record_user_id=u.id_card where to_days(r.create_time) = to_days(now())SELECT r.create_time AS createTime,u.
name
,u.tel FROM place_record r LEFT JOIN place_user u on r.record_user_id=u.id_card WHERE DATE_FORMAT( r.create_time, ‘%Y%m’ ) =DATE_FORMAT( CURDATE( ) , ‘%Y%m’ )SELECT r.create_time AS createTime,u.
name
,u.tel FROM place_record r LEFT JOIN place_user u on r.record_user_id=u.id_card where YEAR(r.create_time)=YEAR(NOW()) ``` -
5.Like
title like concat('%', #{request.title}, '%')
4.function
1.Convert类
String “1,2,3,4” —-> List(1,2,3,4)
-
String str="1,2,3,4" List regionPId = Convert.convert(List.class, str); //hutool
数组转换为集合
-
Object[] a = {"a", "你", "好", "", 1}; List<?> list = Convert.convert(List.class, a); List<?> list = Convert.toList(a);
2.定时任务(task)
-
package com.djfy.antifraud.task; import cn.hutool.core.collection.CollectionUtil; import com.djfy.antifraud.domain.RentalTenantRecord; import com.djfy.antifraud.service.IRentalRoomService; import com.djfy.antifraud.service.IRentalTenantRecordService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.scheduling.annotation.Async; import org.springframework.scheduling.annotation.EnableAsync; import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; import java.time.LocalDateTime; import java.util.List; @Component @EnableScheduling // 1.开启定时任务 @EnableAsync // 2.开启多线程 public class MultithreadScheduleTask { @Autowired private IRentalTenantRecordService tenantRecordService; @Autowired private IRentalRoomService rentalRoomService; @Async @Scheduled(cron = "0 0 12 * * ?") public void first() throws InterruptedException { System.out.println("第一个定时任务开始 : " + LocalDateTime.now().toLocalTime() + "\r\n线程 : " + Thread.currentThread().getName()); rentalRoomService.updateByIds(); } @Async @Scheduled(cron = "0 30 11 * * ?") public void second() throws InterruptedException { System.out.println("第二个定时任务开始 : " + LocalDateTime.now().toLocalTime() + "\r\n线程 : " + Thread.currentThread().getName()); List<RentalTenantRecord> rentalTenantRecords = tenantRecordService.selectRecordByDate(); if(CollectionUtil.isEmpty(rentalTenantRecords)){ for (RentalTenantRecord rentalTenantRecord : rentalTenantRecords) { System.out.println(rentalTenantRecord.getRoomId()); } } } }
3.CommandLineRunner
在使用SpringBoot构建项目时,我们通常有一些预先数据的加载。那么SpringBoot提供了一个简单的方式来实现–CommandLineRunner。
CommandLineRunner是一个接口,我们需要时,只需实现该接口就行。如果存在多个加载的数据,我们也可以使用@Order注解来排序。
@Component @Order(value = 2) public class MyStartupRunner1 implements CommandLineRunner{ @Override public void run(String... strings) throws Exception { System.out.println(">>>>>>>>>>>>>>>服务启动执行,执行加载数据等操作 MyStartupRunner1 order 2 <<<<<<<<<<<<<"); } } @Component @Order(value = 1) public class MyStartupRunner2 implements CommandLineRunner { @Override public void run(String... strings) throws Exception { System.out.println(">>>>>>>>>>>>>>>服务启动执行,执行加载数据等操作 MyStartupRunner2 order 1 <<<<<<<<<<<<<"); } }
4.HandlerInterceptor拦截器
public class MyInterceptor implements HandlerInterceptor{ @Autowired private IpNotService ipNotService; @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler){ log.info(">>>MyInterceptor>>>>>>>在请求处理之前进行调用(Controller方法调用之前)"); String url = request.getRequestURL().toString(); log.info(">>>MyInterceptor>>>>>>>request:{}",url); String token = request.getHeader("token"); log.info("token : [ {} ]", token); String ipAddr = IPUtil.getIpAddr(request); log.info("ipAddr : [ {} ]", ipAddr); IpNot by = ipNotService.findBy("url",ipAddr); if(ObjectUtil.isNull(by)){ return true; } return false; } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { HandlerInterceptor.super.postHandle(request, response, handler, modelAndView); } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { HandlerInterceptor.super.afterCompletion(request, response, handler, ex); } }
5.Json
hutool
String res; //对象 {}
JSONObject jsonObject = JSONUtil.parseObj(res);
String body; //list[{},{}]
JSONArray array = JSONUtil.parseArray(body);
Object o = array.get(0);
6.java Date
1.获取当前时间的前一天
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
Date date = new Date();
Calendar now = Calendar.getInstance();
now.setTime(date);
System.out.println(sdf.format(now.getTime()));
now.add(Calendar.DAY_OF_MONTH, -1);
System.out.println(now.getTime());
System.out.println(sdf.format(now.getTime()));
运行结果:
2017-09-21
Wed Sep 20 14:37:24 CST 2017
2017-09-20
7.拦截
8.pom.xml
1.导入外部jar
<dependency>
<groupId>ctwing.ctg.core</groupId>
<artifactId>ctwing-core</artifactId>
<version>1.0</version>
<scope>system</scope>
<systemPath>${project.basedir}/src/main/resources/lib/ctwing-biz-1.0.jar</systemPath>
</dependency>
9.http远程调用
@Autowired
RestTemplate restTemplate;
@GetMapping("/add")
public String add() {
System.out.println("订单添加");
String forObject = restTemplate.getForObject("http://localhost:8010/stock/add", String.class);
return "Hello"+forObject;
}
10.集合
[list的交集,差集,并集]
需求 | list的方法 | 说明 | 备注 |
---|---|---|---|
交集 | listA.retainAll(listB) | listA内容变为listA和listB都存在的对象 | listB不变 |
差集 | listA.removeAll(listB) | listA中存在的listB的内容去重 | listB不变 |
并集 | listA.removeAll(listB) listA.addAll(listB) |
为了去重,listA先取差集,然后追加全部的listB | listB不变 |
11.生成编号
当前年份
public static void main(String[] args) {
String equipmentNo ="126";
Calendar date = Calendar.getInstance();
String year = String.valueOf(date.get(Calendar.YEAR));
String newEquipmentNo = String.format(year + "%04d", 0);
System.out.println(newEquipmentNo);//20220000
int newEquipment = 0;
if (equipmentNo != null && !equipmentNo.isEmpty()) {
newEquipment = Integer.parseInt(equipmentNo) + 1;
newEquipmentNo = String.format(year + "%04d", newEquipment);
}
System.out.println(newEquipmentNo);//20220127
}
12.YddTool
1.生成当前时间年份编号
/**
* @param equipmentNo 输入1
* @return 202200001
*/
public static String getYearNumber(int equipmentNo ){
Calendar date = Calendar.getInstance();
String year = String.valueOf(date.get(Calendar.YEAR));
String newEquipmentNo = String.format(year + "%05d", equipmentNo);
return newEquipmentNo;
}
13.注解
14.datasource-url
allowMultiQueries=true #可以在sql语句后携带分号,实现多语句执行