笔记:工作中实际用到的Java方法

1.Java8的新特性,可以用来代替foreach来循环list:

list = records.stream().map((item) -> {
    //这里写list循环的方法,例如
    Long categoryId = item.getCategoryId();//分类id
    Category category = categoryService.getById(categoryId);//根据id查询分类对象
    item.setName(category.getName());
    return item;
}).collect(Collectors.toList());

2.对象拷贝BeanUtils.copyProperties

//对象拷贝
//第一个属性是源对象,第二个是拷贝对象,第三个是忽略属性;
//将pageInfo中的属性拷贝到dishDtoPage中,但是records属性忽略掉不拷贝
BeanUtils.copyProperties(pageInfo,dishDtoPage,"records");

3.生成一个id

long orderId = IdWorker.getId();

4.通用的返回类R

/**
 * 通用返回结果类
 * @param <T>
 */
@Data
public class R<T> {

    private Integer code; //编码:1成功,0和其它数字为失败

    private String msg; //错误信息

    private T data; //数据

    private Map map = new HashMap(); //动态数据

    public static <T> R<T> success(T object) {
        R<T> r = new R<T>();
        r.data = object;
        r.code = 1;
        return r;
    }

    public static <T> R<T> error(String msg) {
        R r = new R();
        r.msg = msg;
        r.code = 0;
        return r;
    }
}

5.插入或者更新时自动填充

(CreateUser、UpdateUser、CreateTime、UpdateUser)

//实体类上注解
@TableField(fill = FieldFill.INSERT)
private LocalDateTime createTime;


@TableField(fill = FieldFill.INSERT_UPDATE)
private LocalDateTime updateTime;


@TableField(fill = FieldFill.INSERT)
private Long createUser;


@TableField(fill = FieldFill.INSERT_UPDATE)
private Long updateUser;



/**
 * 自定义元数据对象处理器
 */
@Component
@Slf4j
public class MyMetaObjectHandler implements MetaObjectHandler {
    /**
     * 插入操作,自动填充
     * @param metaObject
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        log.info("公共字段自动填充[Insert]");
        log.info(metaObject.toString());
        metaObject.setValue("createTime", LocalDateTime.now());
        metaObject.setValue("updateTime", LocalDateTime.now());
        metaObject.setValue("createUser", BaseContext.getCurrentId());
        metaObject.setValue("updateUser", BaseContext.getCurrentId());

    }

    /**
     * 更新操作,自动填充
     * @param metaObject
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        log.info("公共字段自动填充[Update]");
        log.info(metaObject.toString());
        metaObject.setValue("updateTime", LocalDateTime.now());
        metaObject.setValue("updateUser", BaseContext.getCurrentId());
    }
}

6.用于获取当前用户的id

/**
 * 基于ThreadLocal封装工具类,用户保存和获取当前登录用户id
 */
public class BaseContext {
    private static ThreadLocal<Long> threadLocal = new ThreadLocal<>();

    /**
     * 设置id
     * @param id
     */
    public static void setCurrentId(Long id){
        threadLocal.set(id);
    }

    /**
     * 获取id
     * @return
     */
    public static Long getCurrentId(){
        return threadLocal.get();
    }
}

7.全局异常类和自定义业务异常类

/**
 * 自定义业务异常类
 */

public class CustomerException extends RuntimeException{
    public CustomerException(String message){
        super(message);
    }
}

/*
    全局异常处理
 */
@ControllerAdvice(annotations = {RestController.class, Controller.class})
@ResponseBody
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 异常处理方法
     * @param ex
     * @return
     */
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R<String> exceptionHandler(SQLIntegrityConstraintViolationException ex){
        log.error(ex.getMessage());
        if(ex.getMessage().contains("Duplicate entry")){
            String[] split = ex.getMessage().split(" ");
            String msg = split[2] + "已存在";
            return R.error(msg);
        }
        return R.error("未知错误");
    }
    /**
     * 异常处理方法
     * @param ex
     * @return
     */
    @ExceptionHandler(CustomerException.class)
    public R<String> exceptionHandler(CustomerException ex){
        log.error(ex.getMessage());

        return R.error(ex.getMessage());
    }
}

8.Date类型带时区的时间转换为不带时区

类定义了中  private Date createTime;
前端转换:
拿到的数据为2023-03-10T10:10:53.000+0800    这是带时区的时间
转换为2023-03-10 10:10:53

在前端用方法  const text = Vue.filter('timeFormatFilter')(new Date(row.createTime).getTime());
string类型的日期转换为时间戳 let startDateStamp = new Date(startDate).getTime();

后端转换:
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
date类型转string:String strdate = format.format(new Date());
string转date类型:Date dateTime = format.parse(deviceOrderVo.getOperateTime());
时间戳Long转string类型: String startDate=format.format(Long.valueOf(longDate));

9.如果后端接收用了@RequestBody,name在api.js中定义方法中参数是data:params,如果没有用这个注解用params:params

在这里插入图片描述

10.JSON类型的数据和list集合相互转换

判断是JSON对象还是JSON数组就看,最外边是{}还是[],{}就是JSON对象。

JSON->List<String>
List<Integer> list = parseArray(json类型的数据, Integer.class);

List<String>->JSON
String str = JSONUtil.toJsonStr(stringList);

JSON类型的字符串->json对象{}
JSONObject resp = JSONObject.parseObject(responseData);

依赖Gson进行JSON和list<实体类>之间的转换
//list转换为json  和 对象转换为json  这个都能实现
Gson gson = new Gson();  
List<User> users = new ArrayList<User>();  
String str = gson.toJson(users);  
 
//json转换为list
Gson gson = new Gson();  
List<User> users = gson.fromJson(str, new TypeToken<List<User>>(){}.getType()); 

 
//json类型的字符串转对象
DeviceOrderVo1 devic = JSON.parseObject(new String(decryptResult), DeviceOrderVo1.class);
//List<对象>类型的字符串转对象
List<DeviceOrderVo1> jsonList = JSONArray.parseArray(new String(decryptResult), DeviceOrderVo1.class); 

// 使用fastjson将对象转换为JSON字符串
String jsonString = JSON.toJSONString(person); 

11.ORA-01843: 无效的月份

mybatis在运行SQL语句时,时间格式上不正确,例如,你的数据格式是’yyyy-MM-dd HH:mm:ss’(2023-04-12 11:21:36),插入到数据库中,但数据库中时间的类型是TIMESTAMP,且分数秒精度为6位,格式为’yyyy-mm-dd hh24:mi:ss’,所以要在插入的sql语句中转换一下

<insert id="InsertInfo">
        insert into tblsubmitinfo(id,createtime,updatetime)
        values
        <foreach collection="list" item="item" index="index" separator=",">
            (#{item.id},
            
            to_date(#{item.createTime},'yyyy-mm-dd hh24:mi:ss'),
            to_date(#{item.updateTime},'yyyy-mm-dd hh24:mi:ss'))
        </foreach>
    </insert>

12.springMVC @ResponseBody决定controller返回的是前端界面还是染回的是数据

@RestController相当于@Controller+@ResponseBody

@RequestMapping(name="提交表单",value="/submitInfo")
@ResponseBody  //加这个注解返回的是数据,不加这个注解返回的是前端视图
public ResponseBean submitInfo(@RequestBody SubmitModel submitModel) {
    log.info("提交表单数据:"  + submitModel );
    ResponseBean responseBean = new ResponseBean();
        try {
            submitService.SubmitInfoAndSyncPdm(submitModel);
        } catch (Exception e) {
            log.info("表单提交失败:{}", LogUtil.logFormat(e));
            responseBean.setResponse(Response.UNKNOWN_ERROR);
            return responseBean;
        }
        responseBean.setResponse(Response.SUCCESS);
        return responseBean;
}

10.JAVA静态(static)方法中依赖注入调用Service层(Dao层)

@Component
public class GetPayload {

    @Autowired
    private HotelUserMapper hotelUserMapper;

    public static GetPayload getPayload;

    //必须有这个初始化的方法才能生效
    @PostConstruct
    public void init(){
        getPayload = this;
        getPayload.hotelUserMapper = this.hotelUserMapper;
    }


    public static String testPost(String mobile) {

        HotelUser hotelUser = getPayload.hotelUserMapper.getAllByMobile(mobile);

    }

}

这种方式也可以在静态方法中访问工具类中的方法

@Component
public class ServerResponse<T> {
    
    public static ServerResponse serverResponse;

    @Autowired
    private RedisUtils redisUtils;
    
    @PostConstruct
    public void init(){
        serverResponse = this;
        serverResponse.redisUtils = this.redisUtils;
    }
    
    public static <T> ServerResponse<T> create(){
            String key = serverResponse.redisUtils.getStringKeyValue("key");
    }

11.传输数据一般是JSON格式的字符串,判断是否是JSON格式的字符串

        //判断是否是JSON格式的字符串
        boolean result = false;
        try {
            Object obj= JSON.parse(jsonData);
            result = true;
        } catch (Exception e) {
            result=false;
        }
        System.out.println(result);

@InitBinder注解,在请求到达controller要执行方法前执行! 可以实现将前台传递过来的日期格式的字符串,自动转化为Date类型

/**
 * 将前台传递过来的日期格式的字符串,自动转化为Date类型
 */
@InitBinder
public void initBinder(WebDataBinder binder)
{
    // Date 类型转换
    binder.registerCustomEditor(Date.class, new PropertyEditorSupport()
    {
        @Override
        public void setAsText(String text)
        {
            setValue(DateUtils.parseDate(text));
        }
    });
}

组件上冒号和@符号的作用

在这里插入图片描述

冒号需要在子组件中props中声明,=号前的total子组件中props中的名字,等于号后的是当前组件的属性或者函数;
@号不需要在子组件props中声明,等于号前的是子组件中需要调用的,一般只在¥emit中调用,比如this.$emit(‘doDelete’, sn),而且一般都是函数不是属性,等于号后的是当前组件的函数。

两种使用多线程的方法

//1.声明一个Thread类
Thread thread = new Thread(new Runnable() {
    public void run () {
        try {
            //执行方法                              
            .........
        }
        catch (JMSException e)
        {
            log.info(LogUtil.logFormat(e));
        }
        
     }
});
thread.setName("ThreadName");
thread.start();
//2.使用三个线程
public class test{
    Private String A;
    Private String B;
    
    public test(String A,String B){
        this.A=A;
        this.B=B;
    }
   
     public static void main(String[] args) {
        for(int i=0;i<3;i++) {
            Thread worker =new Thread(new test("a","b"));
            worker.start();
        }
    }
}

SQL语句中LISTAGG函数,分隔符是换行符的情况

select LISTAGG(CATEGORY ,'\n') WITHIN GROUP (ORDER BY ID) AS CATEGORY
FROM  table

LISTAGG函数,将同一组别的值以分隔符连接起来,在数据库中就是同一列的值拼接起来,
例如:
字段A
a
b
c
使用这个函数LISTAGG(A,“+”)之后就会得到a+b+c
这个时候要是想要使用换行符为分隔符,那么就是“\n”,同时在前端标签中加上属性style=“white-space: pre-line”,这样才能正确显示。

ORACLE数据库插入超长字符串(长度>4000)插入会报错

向表TBLSCANMSGJSON中插入数据,超长字段是SEPMESSAGECONTENT,类型是CLOB类型

插入脚本:
    DECLARE
        longText TBLSCANMSGJSON.SEPMESSAGECONTENT%TYPE; <!-- 数据库中该字段的类型是CLOB -->
    BEGIN
        longText := ''; <!-- 字段内容 -->
        insert into TBLSCANMSGJSON (ID,SEPMESSAGECONTENT)
        values(1,longText);
    END;
 
 mybatis:
 
<insert id="insertLongText">
    DECLARE
        longText TBLSCANMSGJSON.SEPMESSAGECONTENT%TYPE <!-- 数据库中该字段的类型是CLOB -->
    BEGIN
        longText := #{SEPMESSAGECONTENT}; <!--Java对象中取出超长字符串 -->
        insert into TBLSCANMSGJSON (ID,SEPMESSAGECONTENT)
        values(
            #{ID},
            longText, <!-- 将超长字符串插入数据库 -->
        );
    END;
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值