首页
  • 2024.1.1.0
  • 2024.1.1.1
  • 2024.1.2.0
  • 2024.1.3.0
  • Java
  • Linux
  • Deploy
  • Application
关于
友情链接
GitHub (opens new window)

Xiao ku

板砖师傅
首页
  • 2024.1.1.0
  • 2024.1.1.1
  • 2024.1.2.0
  • 2024.1.3.0
  • Java
  • Linux
  • Deploy
  • Application
关于
友情链接
GitHub (opens new window)
  • Springboot集成redis
  • Springboot集成mongodb
  • Springboot集成FastDFS
  • Springboot集成WebSocket
  • Springboot集成kafka
  • Springboot集成Flyway
  • Springboot集成ScheduleTask
  • Validation数据校验规范使用
  • 常用代码
    • Stream流
      • 循环增加某KEY值VALUE
      • 两个List相同Key的值相加
      • List存在null值
      • 获取List中Model嵌套model的id
    • 深拷贝
    • 计时器
    • LocalDateTime
    • LocalTime
    • LocalDate
    • Mybatis实体类关联
      • 实体类
      • 使用内连接+级联属性
    • 正则表达式
    • 注入Bean
      • 定义接口
      • 实现类
      • 配置注入
      • Controller调用
    • 为什么SpringBoot的 jar 可以直接运行
    • MySQL报错
      • onlyfullgroup_by
      • 解决办法-方案一
      • 解决办法-方案二
    • 对象之间属性赋值
    • jackson把实体类转换为json字符串
    • 泛型转实体,Object转实体
    • list根据另外一个list排序
  • Java
xiaoku
2023-03-13
目录

常用代码

# Stream流

# 循环增加某KEY值VALUE

 list.stream().forEach(map -> map.put("AREA_HEIGHT", StrUtil.isBlank(area_height) ? 0 : Double.parseDouble(area_height)));
1

# 两个List相同Key的值相加

     public static void main(String[] args) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("中文", "a");
        map.put("价格",500);


        Map<String, Object> map3 = new HashMap<String, Object>();
        map3.put("中文", "b");
        map3.put("价格",300);

        Map<String, Object> map4 = new HashMap<String, Object>();
        map4.put("中文", "c");
        map4.put("价格",1500);

        List<Map<String, Object>> list1 = new ArrayList<Map<String,Object>>();
        list1.add(map);
        list1.add(map3);

        List<Map<String, Object>> list2 = new ArrayList<Map<String,Object>>();
        list2.add(map);
        list2.add(map4);
        List<Map<String, Object>> list = new ArrayList<Map<String,Object>>();
        list.addAll(list1);
        list.addAll(list2);

        List<Map<String,Object>> result =new ArrayList<>();
        Map<String, List<Map<String, Object>>> glist = list.stream().collect(Collectors.groupingBy(e -> e.get("中文").toString()));

        glist.forEach((k,slist)->{
            Map<String,Object> nmap=new HashMap<>();
            IntSummaryStatistics sumcc = slist.stream().collect(Collectors.summarizingInt(e->Integer.valueOf(e.get("价格").toString())));
            nmap.put("中文", slist.get(0).get("中文"));
            nmap.put("价格", sumcc.getSum());//求和
            result.add(nmap);
        });
        System.out.println("--------testMerge-------------");
        result.forEach(x->{
            System.out.println(x);
        });

    }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41

# List存在null值

Not showing null elements

note

把null元素移除:

list.removeAll(Collections.singleton(null));
1

# 获取List中Model嵌套model的id

 List<String> ids = checkingTheListItems.stream().map(InsRecordToSeVo:: getInspectionRecord).map(InspectionRecord :: getTaskProjectId).collect(Collectors.toList());
1

# 深拷贝

 SerializationUtils.clone(xxxx)
1

# 计时器

StopWatch stopWatch = new StopWatch();

stopWatch.start("深拷贝");
stopWatch.stop();

log.info(stopWatch.prettyPrint());
1
2
3
4
5
6

# LocalDateTime

// 获取当前日期时间
LocalDateTime localDateTime = LocalDateTime.now();
// 设置日期
LocalDateTime localDateTime1 = LocalDateTime.of(2019, Month.SEPTEMBER, 10, 14, 46, 56);
LocalDateTime localDateTime2 = LocalDateTime.of(localDate, localTime);
LocalDateTime localDateTime3 = localDate.atTime(localTime);
LocalDateTime localDateTime4 = localTime.atDate(localDate);
// 获取LocalDate
LocalDate localDate2 = localDateTime.toLocalDate();
// 获取LocalTime
LocalTime localTime2 = localDateTime.toLocalTime();
1
2
3
4
5
6
7
8
9
10
11

# LocalTime

 // 获取当前时间
LocalTime now = LocalTime.now();
// 设置时间
LocalTime localTime = LocalTime.of(13, 51, 10);
//获取小时
int hour = localTime.getHour();    // 结果:13
int hour1 = localTime.get(ChronoField.HOUR_OF_DAY); // 结果:13
//获取分
int minute = localTime.getMinute();  // 结果:51
int minute1 = localTime.get(ChronoField.MINUTE_OF_HOUR); // 结果:51
//获取秒
int second = localTime.getSecond();   // 结果:10
int second1 = localTime.get(ChronoField.SECOND_OF_MINUTE); // 结果:10
1
2
3
4
5
6
7
8
9
10
11
12
13

# LocalDate

 // 获取当前日期
LocalDate now = LocalDate.now();
// 设置日期
LocalDate localDate = LocalDate.of(2019, 9, 10);
// 获取年
int year = localDate.getYear();     //结果:2019
int year1 = localDate.get(ChronoField.YEAR); //结果:2019
// 获取月
Month month = localDate.getMonth();   // 结果:SEPTEMBER
int month1 = localDate.get(ChronoField.MONTH_OF_YEAR); //结果:9
// 获取日
int day = localDate.getDayOfMonth();   //结果:10
int day1 = localDate.get(ChronoField.DAY_OF_MONTH); // 结果:10
// 获取星期
DayOfWeek dayOfWeek = localDate.getDayOfWeek();   //结果:TUESDAY
int dayOfWeek1 = localDate.get(ChronoField.DAY_OF_WEEK); //结果:2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

# Mybatis实体类关联

# 实体类

 @Data
@ToString
@NoArgsConstructor
public class IdCard {
    private Integer id;
    private String number;
    private Date expiredTime;

    public IdCard(Integer id) {
        this.id = id;
    }

}


@Data
@ToString
@NoArgsConstructor
public class Person {
    protected Integer id;
    protected String name;
    protected IdCard idCard;

    public Person(Integer id) {
        this.id = id;
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27

对于关联属性的配置,有5种方式

参考博客:blog (opens new window)

# 使用内连接+级联属性

 <?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="com.sunwii.mybatis.mapper.PersonMapper">
    <resultMap type="PersonResult" id="PersonMap">
        <id property="id" column="id" />
        <result property="name" column="name" />
        <!-- 一对一关联:单向。方式零:使用级联属性 -->
        <result property="idCard.id" column="cid"/>
        <result property="idCard.number" column="number"/>
        <result property="idCard.expiredTime" column="expired_time"/>
    </resultMap>
    <select id="selectById" parameterType="Integer"
        resultMap="PersonMap">
        select p.id id, p.name name,c.id cid,c.number
        number,c.expired_time expired_time from t_person p
        inner join t_idcard
        c on p.idcard_id=c.id and p.id=#{id}
    </select>
</mapper>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22

# 正则表达式

速查手册: blog (opens new window)

# 注入Bean

需求:工程启动时,执行实现类initAll()方法(非监听)

# 定义接口

public interface MapPosServer {
     void initAll();
     void destructionAll();
      void other();
}
1
2
3
4
5

# 实现类

 @Slf4j
@Service
public class MapPosServerImpl implements MapPosServer  {

    @Override
    public void initAll() {
        log.info("开始初始化");
       
    }

    /**
     * 注销所有地图
     * @return
     */
    @Override
    public void destructionAll() {
        log.info("开始注销所有地图");
       
    }


    @Override
    public void other() {
        log.info("其他方法");
       
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27

# 配置注入

import cn.ok96.service.MapPosServerImpl;
import cn.ok96.service.impl.MapPositioningServerImpl;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;

@Configuration
public class MapPosConfig  {


    public  MapPosConfig(){
        System.out.println("初始化");
    }

    @Bean(name="MapPosServerInit",initMethod="initAll",destroyMethod="destructionAll")
    @Scope("prototype")
    public MapPosServer testBean() {
        return new MapPosServerImpl();
    }

}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

# Controller调用

 @Resource(name="MapPosServerInit")
    private MapPosServer mapPosServer;
    
    @GetMapping()
    public String xxxx(){
        mapPosServer.other();
        return "ok";
    }
1
2
3
4
5
6
7
8

# 为什么SpringBoot的 jar 可以直接运行

文章: blog (opens new window)

# MySQL报错

# only_full_group_by

报错信息为:

### Cause: java.sql.SQLSyntaxErrorException: Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'inspection.ars_inspection_record.TASK_ID' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by
; bad SQL grammar []; nested exception is java.sql.SQLSyntaxErrorException: Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'inspection.ars_inspection_record.TASK_ID' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by
    at org.springframework.jdbc.support.SQLExceptionSubclassTranslator.doTranslate(SQLExceptionSubclassTranslator.java:93)
1
2
3

# 解决办法-方案一

配置文件my.cnf增加模式,然后重启

[mysqld]
# 设置模式
sql_mode =STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION
1
2
3

# 解决办法-方案二

错误SQL为

select A.column1, A.column2 from table as A group by column1
1

按column1进行分组 那么结果就是这个组内的cloumn1都是相同的,但是column2却没有限制,也就是说可能相同 也可能不同,那么数据库不知道column2该返回什么值给你

故:在group by后面追加上column2就可以了,意义相当于按照 由column1和column2拼接成的联合字段进行分组

select A.column1, A.column2 from table as A group by column1 , column2
1

# 对象之间属性赋值

BeanUtils是深拷贝,还是浅拷贝?
是浅拷贝。只是调用子对象的set方法,并没有将所有属性拷贝。(也就是说,引用的一个内存地址)

YYYY xxxyyData=XXX.getData();
ZZZZ dbtoSave =new  ZZZZ();
BeanUtils.copyProperties(xxxyyData,dbtoSave);
1
2
3

# jackson把实体类转换为json字符串

在springboot2中自动配的是jackson。但没有JSONObject。
导致在Controller接口中,@Mapping返回实体使用的是jackson序列化,而其他地方使用com.alibaba.fastjson的toJSONString两者字段不一致

使用jackson转换可以使用:

       ObjectMapper mapper = new ObjectMapper();
       ResponseBean res=new ResponseBean();
        res.setMes("asjdadadsad");
        res.setResData("sadsadsad");
        res.setState("1");
        try {
           String a =  mapper.writeValueAsString(res);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
1
2
3
4
5
6
7
8
9
10

# 泛型转实体,Object转实体

可以使用上述ObjectMapper mapper = new ObjectMapper();

@Getter
@Setter
public class YYY<T> {
   @ApiModelProperty("业务数据")
    private T data;
}

ObjectMapper mapper = new ObjectMapper();
XXXX xxxList=mapper.readValue(mapper.writeValueAsString(YYY.getData()), XXXX.class);
1
2
3
4
5
6
7
8
9

Object转实体

ObjectMapper objectMapper = new ObjectMapper();
Zjzfxmsp zfsp = objectMapper.convertValue(object, Zjzfxmsp.class);
1
2

# list根据另外一个list排序

原版代码

public static void main(String[] args) {
   String[] regulation = {"诸葛亮","鲁班","xzcx","貂蝉","吕布"};
   final List regulationOrder = Arrays.asList(regulation);
   String[] ordered = {"nice","貂蝉","诸葛亮","xzcx","吕布","貂蝉","鲁班","诸葛亮","貂蝉","鲁班","诸葛亮","hahahahah","adsad"};
   List orderedList = Arrays.asList(ordered);
   Collections.sort(orderedList, new Comparator()
   {
      public int compare(String o1, String o2)
      {
         int io1 = regulationOrder.indexOf(o1);
         int io2 = regulationOrder.indexOf(o2);
         if(io1 == -1){
            return 1;
         }
         if(io2 == -1){
            return -1;
         }
         return io1 - io2;
      }
   });
   System.out.println(orderedList);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22

修改版

List<String> order = orderParamsList.stream().map(v ->
        v.getCode().replace("xxx", "").replace("yyy", "")
).collect(Collectors.toList());

Collections.sort(resultDuList, new Comparator<GroupVo>() {
    @Override
    public int compare(GroupVo o1, GroupVo o2) {
        int io1 = order.indexOf(o1.getMembership());
        int io2 = order.indexOf(o2.getMembership());
        if (io1 == -1) {
            return 1;
        }
        if (io2 == -1) {
            return -1;
        }
        return io1 - io2;
    }
});
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
上次更新: 2023/03/13, 03:16:04
Validation数据校验规范使用

← Validation数据校验规范使用

Copyright © 2019-2024
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式