java+postgresql+swagger-单表批量和循环insert、delete操作(八)

一、循环写入:

入参json格式:

复制代码
[{"devicenumber": "swaggertest01","devicestate": 2,"locationtype": 2,"devicelat": 34.331913,"devicelng": 113.278743,"batterypct": 99.9,"locationtime": "2025-04-08 13:20:01","lasttime": "2025-04-08 13:20:01","pointsource": 9999,"speed": 23.23},{ "devicenumber": "swaggertest02","devicestate": 2,"locationtype": 2,"devicelat": 34.331913,"devicelng": 113.278743,"batterypct": 99.9,"locationtime": "2025-04-08 13:20:01","lasttime": "2025-04-08 13:20:01","pointsource": 9999,"speed": 23.23},{"devicenumber": "41001061710","devicestate": 2,"locationtype": 2,"devicelat": 34.331913,"devicelng": 113.278743,"batterypct": 99.9,"locationtime": "2025-04-08 13:20:01","lasttime": "2025-04-08 13:20:01","pointsource": 9999,"speed": 23.23},{"devicenumber": "swaggertest03","devicestate": 2,"locationtype": 2,"devicelat": 34.331913,"devicelng": 113.278743,"batterypct": 99.9,"locationtime": "2025-04-08 13:20:01","lasttime": "2025-04-08 13:20:01","pointsource": 9999,"speed": 23.23}]

1、实体:

复制代码
package com.example.springbootmybatisplus.entity;

import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.fasterxml.jackson.annotation.JsonFormat;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import org.springframework.format.annotation.DateTimeFormat;

import java.io.Serializable;
import java.math.BigDecimal;
import java.util.Date;
@Data
@TableName(value = "tm_devicestatus")
@ApiModel(value = "设备定位信息")
public class TmDeviceStatus implements Serializable {
    /**
     * 设备号
     */
    @TableId(value = "devicenumber")
    @ApiModelProperty(value = "设备号")
    private String deviceNumber;

    /**
     * 点源
     */
    @TableField(value = "pointsource")
    @ApiModelProperty(value = "点源")
    private Short pointSource;

    /**
     * 设备状态:0 未启用;1 离线;2 静止;3 行驶中
     */
    @TableField(value = "devicestate")
    @ApiModelProperty(value = "设备状态:0 未启用;1 离线;2 静止;3 行驶中")
    private Short deviceState;

    /**
     * 定位方式:0 GPS;1 基站;2 WiFi;3 北斗;4 GPS/北斗混合
     */
    @TableField(value = "locationtype")
    @ApiModelProperty(value = "定位方式:0 GPS;1 基站;2 WiFi;3 北斗;4 GPS/北斗混合")
    private Short locationType;

    /**
     * 原始纬度
     */
    @TableField(value = "devicelat")
    @ApiModelProperty(value = "原始纬度")
    private BigDecimal deviceLat;

    /**
     * 原始经度
     */
    @TableField(value = "devicelng")
    @ApiModelProperty(value = "原始经度")
    private BigDecimal deviceLng;

    /**
     * 当前电量
     */
    @TableField(value = "batterypct")
    @ApiModelProperty(value = "当前电量")
    private BigDecimal batteryPct;

    /**
     * 定位时间
     */
    @JsonFormat(locale = "zh", timezone = "GMT+8", pattern = "yyyy-MM-dd HH:mm:ss")
    @DateTimeFormat
    @TableField(value = "locationtime")
    @ApiModelProperty(value = "定位时间")
    private Date locationTime;

    /**
     * 通讯时间
     */
    @JsonFormat(locale = "zh", timezone = "GMT+8", pattern = "yyyy-MM-dd HH:mm:ss")
    @DateTimeFormat
    @TableField(value = "lasttime")
    @ApiModelProperty(value = "通讯时间")
    private Date lastTime;

    /**
     * 速度(km/h)
     */
    @TableField(value = "speed")
    @ApiModelProperty(value = "速度(km/h)")
    private BigDecimal speed;

    /**
     * 备注json
     */
    @TableField(value = "jsonstring")
    private String jsonString;
    /**
     * 创建时间
     */
    @TableField(value = "createdat")
    @ApiModelProperty(value = "创建时间")
    private Date createdAt;
    /**
     * 创建操作人
     */
    @TableField(value = "createdbyid")
    @ApiModelProperty(value = "创建操作人")
    private String createdById;
    /**
     * 更新时间
     */
    @TableField(value = "updatedat")
    @ApiModelProperty(value = "更新时间")
    private Date updatedAt;
    /**
     * 更新操作人
     */
    @TableField(value = "updatedbyid")
    @ApiModelProperty(value = "更新操作人")
    private String updatedById;
    /**
     * 删除时间
     */
    @TableField(value = "deletedat")
    @ApiModelProperty(value = "删除时间")
    private Date deletedAt;
    /**
     * 删除操作人
     */
    @TableField(value = "deletedbyid")
    @ApiModelProperty(value = "删除操作人")
    private String deletedById;
    /**
     * 是否删除(f否t是)
     */
    @TableField(value = "deleted")
    private Boolean deleted;
}

2、Mapper:

复制代码
@Mapper
public interface TmDeviceStatusMapper extends BaseMapper<TmDeviceStatus> {
    @Select("select * from tm_devicestatus where devicenumber = #{deviceNumber} and pointsource=#{pointSource}")
    TmDeviceStatus existsTmDeviceStatus(@Param("deviceNumber") String deviceNumber, @Param("pointSource") short pointSource);
}

3、Service:

复制代码
package com.example.springbootmybatisplus.service;

import com.alibaba.fastjson.JSONObject;
import com.example.springbootmybatisplus.entity.TmDeviceStatus;
import com.example.springbootmybatisplus.mapper.TmDeviceStatusMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class TmDeviceStatusService {
    @Autowired
    private TmDeviceStatusMapper tmDeviceStatusMapper;

    private static final Logger log = LoggerFactory.getLogger(TmDeviceStatusService.class);

    public void insertTmDeviceStatus(String msg) {
        try {
            List<TmDeviceStatus> jsonArray = JSONObject.parseArray(msg, TmDeviceStatus.class);
            for (int i = 0; i < jsonArray.size(); i++) {
                TmDeviceStatus tmDeviceStatus = jsonArray.get(i);
                TmDeviceStatus tmDeviceStatus1 = tmDeviceStatusMapper.existsTmDeviceStatus(tmDeviceStatus.getDeviceNumber(), tmDeviceStatus.getPointSource());
                if (tmDeviceStatus1 != null) {
                    tmDeviceStatusMapper.deleteById(tmDeviceStatus.getDeviceNumber());
                    log.info("设备:{}的定位信息在表中存在,删除此设备定位信息", tmDeviceStatus.getDeviceNumber());
                }
                tmDeviceStatusMapper.insert(tmDeviceStatus);
                log.info("设备:{}的定位信息已写入表中", tmDeviceStatus.getDeviceNumber());
            }
        } catch (Exception e) {
            log.error("异常信息:" + e.getMessage());
        }
    }
}

4、Controller:

复制代码
package com.example.springbootmybatisplus.contronller;

import com.example.springbootmybatisplus.entity.TmDeviceStatus;
import com.example.springbootmybatisplus.service.TmDeviceStatusService;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("/tm-devicestatus")
@Api(tags = "设备状态")
public class TmDeviceStatusController {
    @Autowired
    private TmDeviceStatusService tmDeviceStatusService;

    @PostMapping("/insert1")
    public ResponseEntity<String> insert1(@RequestBody String msg) {
        try {
            tmDeviceStatusService.insertTmDeviceStatus(msg);
            return ResponseEntity.status(HttpStatus.CREATED).body("Success");
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Failed");
        }
    }

}

5、调用接口打印日志:

二、批量操作:

入参json格式:

复制代码
[{"batteryPct": 88,"deviceLat": 34.331913,"deviceLng": 113.278743,"deviceNumber": "swaggertest01","deviceState": 2,"lastTime": "2025-04-10 02:57:09","locationTime": "2025-04-10 02:57:09","locationType": 1,"pointSource": 9999,"speed": 23.2},{"batteryPct": 88,"deviceLat": 34.331913,"deviceLng": 113.278743,"deviceNumber": "swaggertest02","deviceState": 2,"lastTime": "2025-04-10 02:57:09","locationTime": "2025-04-10 02:57:09","locationType": 1,"pointSource": 9999,"speed": 23.2}]

1、实体:

和上面的一样。

2、Mapper:

复制代码
@Mapper
public interface TmDeviceStatusMapper extends BaseMapper<TmDeviceStatus> {
    int deleteTmDeviceStatusList(@Param("list") List<String> devices);

    int insertTmDeviceStatusBatch(@Param("list") List<TmDeviceStatus> deviceStatus);
}

3、xml:

复制代码
<?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.example.springbootmybatisplus.mapper.TmDeviceStatusMapper">
    <delete id="deleteTmDeviceStatusList" parameterType="java.util.List">
        delete from tm_devicestatus where devicenumber in
        <foreach collection="list" item="item" open="(" separator="," close=")">
            #{item,jdbcType=VARCHAR}
        </foreach>
    </delete>
    <insert id="insertTmDeviceStatusBatch" parameterType="java.util.List">
        insert into tm_devicestatus(
        "devicenumber",
        "devicestate",
        "locationtype",
        "devicelat",
        "devicelng",
        "batterypct",
        "locationtime",
        "lasttime",
        "pointsource",
        "speed",
        "jsonstring"
        )
        values
        <foreach collection="list" item="item" index="idx" separator=",">
            (
            #{item.deviceNumber,jdbcType=VARCHAR},
            #{item.deviceState,jdbcType=SMALLINT},
            #{item.locationType,jdbcType=SMALLINT},
            #{item.deviceLat,jdbcType=DECIMAL},
            #{item.deviceLng,jdbcType=DECIMAL},
            #{item.batteryPct,jdbcType=DECIMAL},
            #{item.locationTime,jdbcType=TIMESTAMP},
            #{item.lastTime,jdbcType=TIMESTAMP},
            #{item.pointSource,jdbcType=SMALLINT},
            #{item.speed,jdbcType=DECIMAL},
            #{item.jsonString,jdbcType=VARCHAR}
            )
        </foreach>
    </insert>
</mapper>

4、Service:

复制代码
@Service
public class TmDeviceStatusService {
    @Autowired
    private TmDeviceStatusMapper tmDeviceStatusMapper;

    private static final Logger log = LoggerFactory.getLogger(TmDeviceStatusService.class);

    public void insertTmDeviceStatusBatch(List<TmDeviceStatus> list) {
        if (list == null || list.isEmpty()) {
            log.warn("插入的设备列表数据为空,无需处理");
            return;
        } else {
            try {
                List<String> devices = list.stream()
                        .map(TmDeviceStatus::getDeviceNumber)
                        .collect(Collectors.toList());
                log.info("待处理设备列表:{}", devices);
                tmDeviceStatusMapper.deleteTmDeviceStatusList(devices);
                log.info("list:{}", list);
                for (TmDeviceStatus item:list){
                    item.setJsonString(JSONObject.toJSONString(item));
                }
                tmDeviceStatusMapper.insertTmDeviceStatusBatch(list);
            } catch (Exception e) {
                log.error("异常信息:" + e.getMessage());
            }
        }
    }


}

5、Controller:

复制代码
@RestController
@RequestMapping("/tm-devicestatus")
@Api(tags = "设备状态")
public class TmDeviceStatusController {
    @Autowired
    private TmDeviceStatusService tmDeviceStatusService;

    @PostMapping("/insert2")
    public ResponseEntity<String> insert2(@RequestBody List<TmDeviceStatus> list) {
        try {
            tmDeviceStatusService.insertTmDeviceStatusBatch(list);
            return ResponseEntity.status(HttpStatus.CREATED).body("Success");
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Failed");
        }
    }

}

6、调用接口打印日志

相关推荐
Hanson Huang27 分钟前
【数据结构】堆排序详细图解
java·数据结构·排序算法·堆排序
Susea&28 分钟前
数据结构初阶:队列
c语言·开发语言·数据结构
慕容静漪30 分钟前
如何本地安装Python Flask并结合内网穿透实现远程开发
开发语言·后端·golang
ErizJ32 分钟前
Golang|锁相关
开发语言·后端·golang
GOTXX36 分钟前
【Qt】Qt Creator开发基础:项目创建、界面解析与核心概念入门
开发语言·数据库·c++·qt·图形渲染·图形化界面·qt新手入门
猿小喵38 分钟前
记录一次TDSQL网关夯住故障
运维·数据库·mysql
电商api接口开发42 分钟前
如何在C#中使用LINQ对数据库进行查询操作?
数据库·c#·linq
路在脚下@44 分钟前
Redis实现分布式定时任务
java·redis
搬砖工程师Cola1 小时前
<C#>在 .NET 开发中,依赖注入, 注册一个接口的多个实现
开发语言·c#·.net
xrkhy1 小时前
idea的快捷键使用以及相关设置
java·ide·intellij-idea