Browse Source

jpa替换为mybatisplus

yangwanyi 2 years ago
parent
commit
04cb011c96

+ 4 - 3
pom.xml

@@ -20,6 +20,7 @@
         <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
         <protostuff.version>1.0.10</protostuff.version>
         <objenesis.version>2.4</objenesis.version>
+        <mybatis-plus.version>3.3.0</mybatis-plus.version>
     </properties>
 
     <dependencies>
@@ -130,10 +131,10 @@
             <artifactId>druid-spring-boot-starter</artifactId>
             <version>1.1.22</version>
         </dependency>
-        <!-- spring-data-jpa -->
         <dependency>
-            <groupId>org.springframework.boot</groupId>
-            <artifactId>spring-boot-starter-data-jpa</artifactId>
+            <groupId>com.baomidou</groupId>
+            <artifactId>mybatis-plus-boot-starter</artifactId>
+            <version>3.3.0</version>
         </dependency>
         <dependency>
             <groupId>org.springframework.boot</groupId>

+ 2 - 0
src/main/java/com/persagy/ZktProjectAlarmApplication.java

@@ -1,6 +1,7 @@
 package com.persagy;
 
 import com.github.dadiyang.autologging.aop.annotation.AutoLogAll;
+import org.mybatis.spring.annotation.MapperScan;
 import org.springframework.boot.SpringApplication;
 import org.springframework.boot.autoconfigure.SpringBootApplication;
 import org.springframework.scheduling.annotation.EnableScheduling;
@@ -8,6 +9,7 @@ import org.springframework.scheduling.annotation.EnableScheduling;
 @SpringBootApplication
 @EnableScheduling
 @AutoLogAll
+@MapperScan(basePackages = "com.persagy.mapper")
 public class ZktProjectAlarmApplication {
 
     public static void main(String[] args) {

+ 63 - 41
src/main/java/com/persagy/controller/HelloWorld.java

@@ -1,19 +1,8 @@
 package com.persagy.controller;
 
 
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.concurrent.ConcurrentHashMap;
-import java.util.concurrent.atomic.AtomicInteger;
-
-import org.springframework.beans.factory.annotation.Autowired;
-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 cn.hutool.core.util.ObjectUtil;
+import cn.hutool.core.util.StrUtil;
 import com.alibaba.fastjson.JSONObject;
 import com.persagy.cache.AlarmInfoCache;
 import com.persagy.constant.CommonConst;
@@ -21,15 +10,25 @@ import com.persagy.entity.AlarmDefine;
 import com.persagy.entity.AlarmState;
 import com.persagy.entity.NettyMessage;
 import com.persagy.entity.ZktAlarmRecordDO;
+import com.persagy.mapper.AlarmRecordMapper;
 import com.persagy.netty.client.NettyClient;
-import com.persagy.repository.AlarmRecordRepository;
 import com.persagy.service.AlarmHandleService;
+import com.persagy.service.IAlarmRecordService;
 import com.persagy.utils.LockUtil;
-
-import cn.hutool.core.util.ObjectUtil;
-import cn.hutool.core.util.StrUtil;
 import io.swagger.annotations.Api;
 import lombok.extern.slf4j.Slf4j;
+import org.springframework.beans.factory.annotation.Autowired;
+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.ArrayList;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.atomic.AtomicInteger;
 
 @Api(tags = "hello")
 @RestController
@@ -39,10 +38,13 @@ public class HelloWorld {
     @Autowired
     AlarmHandleService alarmHandleService;
     @Autowired
-    AlarmRecordRepository alarmRecordRepository;
+    AlarmRecordMapper alarmRecordMapper;
     @Autowired
     NettyClient nettyClient;
-    
+
+    @Autowired
+    private IAlarmRecordService alarmRecordService;
+
     @PostMapping("/createAlarm")
     public String createAlarm(@RequestBody JSONObject jsonObject) throws Exception {
         NettyMessage nettyMessage = new NettyMessage(5);
@@ -57,6 +59,23 @@ public class HelloWorld {
         return "hello world!";
     }
 
+    @PostMapping("/testSave")
+    public String testSave(@RequestBody ZktAlarmRecordDO data) throws Exception {
+        ZktAlarmRecordDO zktAlarmRecordDO = alarmRecordService.findById(data.getDefinitionId()).orElse(data);
+        try {
+            System.out.println(JSONObject.toJSONString(zktAlarmRecordDO));
+
+            zktAlarmRecordDO.setObjId(data.getObjId());
+            zktAlarmRecordDO.setItemId(data.getItemId());
+            zktAlarmRecordDO.setAlarmId(data.getAlarmId());
+            int i = this.alarmRecordService.replaceSave(zktAlarmRecordDO);
+            System.out.println("执行结果:" + i);
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+        return "hello world!";
+    }
+
     @PostMapping("/testMesage")
     public String testMesage(@RequestBody JSONObject jsonObject) throws Exception {
         NettyMessage nettyMessage = new NettyMessage(4);
@@ -102,15 +121,18 @@ public class HelloWorld {
     @PostMapping("/test3")
     public ArrayList<ZktAlarmRecordDO> test3(@RequestBody JSONObject jsonObject) throws Exception {
         String defineId = AlarmInfoCache.getAlarmDefineId(jsonObject);
-        ZktAlarmRecordDO zktAlarmRecordDO = alarmRecordRepository.findById(defineId).orElse(new ZktAlarmRecordDO());
+        ZktAlarmRecordDO zktAlarmRecordDO = this.alarmRecordMapper.selectById(defineId);
+        if (null == zktAlarmRecordDO) {
+            zktAlarmRecordDO = new ZktAlarmRecordDO();
+        }
         zktAlarmRecordDO.setDefinitionId(defineId);
         zktAlarmRecordDO.setItemCode(jsonObject.getString("itemCode"));
         zktAlarmRecordDO.setObjId(jsonObject.getString("objId"));
         zktAlarmRecordDO.setItemId(jsonObject.getString("itemId"));
         zktAlarmRecordDO.setAlarmId(jsonObject.getString("id"));
-        ZktAlarmRecordDO save = alarmRecordRepository.save(zktAlarmRecordDO);
-        log.info("保存结果为:{}", save);
-        Iterable<ZktAlarmRecordDO> all = alarmRecordRepository.findAll();
+        int num = this.alarmRecordMapper.replaceSave(zktAlarmRecordDO);
+        log.info("保存结果为:{}", num);
+        Iterable<ZktAlarmRecordDO> all = this.alarmRecordMapper.selectList(null);
         Iterator<ZktAlarmRecordDO> iterator = all.iterator();
         ArrayList<ZktAlarmRecordDO> list = new ArrayList<>();
         while (iterator.hasNext()) {
@@ -121,35 +143,35 @@ public class HelloWorld {
 
     @PostMapping("/test4")
     public Object test4(@RequestBody JSONObject jsonObject) throws Exception {
-    	String objId = jsonObject.getString("objId");
-    	String itemId = jsonObject.getString("itemId");
-    	if (StrUtil.isAllNotBlank(objId, itemId)) {
-    		String defineId = AlarmInfoCache.getAlarmDefineId(jsonObject);
-    		return AlarmInfoCache.getAlarmDefinitionById(defineId);
-		}
-    	
-    	JSONObject result = new JSONObject();
+        String objId = jsonObject.getString("objId");
+        String itemId = jsonObject.getString("itemId");
+        if (StrUtil.isAllNotBlank(objId, itemId)) {
+            String defineId = AlarmInfoCache.getAlarmDefineId(jsonObject);
+            return AlarmInfoCache.getAlarmDefinitionById(defineId);
+        }
+
+        JSONObject result = new JSONObject();
         ConcurrentHashMap<String, AlarmDefine> alarmDefineMap = AlarmInfoCache.getAlarmDefineMap();
         if (ObjectUtil.isNotEmpty(alarmDefineMap)) {
-        	result.put("count", alarmDefineMap.size());
-        	result.put("alarmDefineMap", alarmDefineMap);
+            result.put("count", alarmDefineMap.size());
+            result.put("alarmDefineMap", alarmDefineMap);
             return result;
         }
         return new HashMap<>();
     }
-    
+
     @PostMapping("/test5")
     public AlarmState getAlarmState(@RequestBody JSONObject jsonObject) throws Exception {
-    	String defineId = AlarmInfoCache.getAlarmDefineId(jsonObject);
-    	return AlarmInfoCache.getAlarmState(defineId);
+        String defineId = AlarmInfoCache.getAlarmDefineId(jsonObject);
+        return AlarmInfoCache.getAlarmState(defineId);
     }
-    
+
     @PostMapping("/test6")
     public AlarmState setAlarmState(@RequestBody JSONObject jsonObject) throws Exception {
-    	String defineId = AlarmInfoCache.getAlarmDefineId(jsonObject);
-    	AlarmState alarmState = AlarmInfoCache.getAlarmState(defineId);
-    	alarmState.setState(jsonObject.getString("state"));
-    	return AlarmInfoCache.getAlarmState(defineId);
+        String defineId = AlarmInfoCache.getAlarmDefineId(jsonObject);
+        AlarmState alarmState = AlarmInfoCache.getAlarmState(defineId);
+        alarmState.setState(jsonObject.getString("state"));
+        return AlarmInfoCache.getAlarmState(defineId);
     }
 
 }

+ 0 - 1
src/main/java/com/persagy/entity/AlarmRecord.java

@@ -9,7 +9,6 @@ import lombok.Builder;
 import lombok.Data;
 import lombok.NoArgsConstructor;
 
-import javax.persistence.Transient;
 import java.io.Serializable;
 import java.time.LocalDateTime;
 import java.util.Date;

+ 18 - 21
src/main/java/com/persagy/entity/ZktAlarmRecordDO.java

@@ -3,6 +3,9 @@ package com.persagy.entity;
 
 import com.alibaba.fastjson.JSONObject;
 import com.alibaba.fastjson.annotation.JSONField;
+import com.baomidou.mybatisplus.annotation.TableField;
+import com.baomidou.mybatisplus.annotation.TableId;
+import com.baomidou.mybatisplus.annotation.TableName;
 import io.swagger.annotations.ApiModel;
 import io.swagger.annotations.ApiModelProperty;
 import lombok.AllArgsConstructor;
@@ -10,10 +13,6 @@ import lombok.Builder;
 import lombok.Data;
 import lombok.NoArgsConstructor;
 
-import javax.persistence.Column;
-import javax.persistence.Entity;
-import javax.persistence.Id;
-import javax.persistence.Table;
 import java.io.Serializable;
 import java.util.Date;
 
@@ -25,37 +24,33 @@ import java.util.Date;
 @Builder
 @NoArgsConstructor
 @AllArgsConstructor
-@Entity
-@Table(name = "zkt_alarm_record")
+@TableName("zkt_alarm_record")
 public class ZktAlarmRecordDO implements Serializable {
     private static final long serialVersionUID = 1L;
     /**
      * 报警定义ID
      */
-    @Id
-//    @GeneratedValue(strategy = GenerationType.IDENTITY) // strategy 设置使用数据库主键自增策略;
-//            ,generator = "JDBC") // generator 设置插入完成后,查询最后生成的 ID 填充到该属性中。
-    @Column(name = "definition_id", nullable = false)
+    @TableId(value = "definition_id")
     private String definitionId;
 
     /**
      * 报警条目编码
      */
-    @Column(name = "item_code", nullable = false)
+    @TableField(value = "item_code")
     @ApiModelProperty(value = "报警条目编码")
     private String itemCode;
 
     /**
      * 报警对象ID
      */
-    @Column(name = "obj_id", nullable = false)
+    @TableField(value = "obj_id")
     @ApiModelProperty(value = "报警对象ID")
     private String objId;
 
     /**
      * 类型id
      */
-    @Column(name = "item_id", nullable = false)
+    @TableField(value = "item_id")
     @ApiModelProperty(value = "报警类型id")
     private String itemId;
 
@@ -63,61 +58,63 @@ public class ZktAlarmRecordDO implements Serializable {
      * 报警定义对应最新一条报警记录状态
      * 1-产生 2-恢复 3-过期
      */
-    @Column(name = "state")
+    @TableField(value = "state")
     @ApiModelProperty(value = "报警定义对应最新一条报警记录状态")
     private String state;
 
     /**
      * 报警定义对应最新一条报警记录ID
      */
-    @Column(name = "alarm_id")
+    @TableField(value = "alarm_id")
     @ApiModelProperty(value = "报警定义对应最新一条报警记录ID")
     private String alarmId;
 
     /**
      * 报警时间
      */
-    @Column(name = "alarm_time")
+    @TableField(value = "alarm_time")
     @ApiModelProperty(value = "报警时间")
     private String alarmTime;
 
     /**
      * 报警生效结束时间(报警过期时间)
      */
-    @Column(name = "effect_end_time")
+    @TableField(value = "effect_end_time")
     @ApiModelProperty(value = "报警生效结束时间(报警过期时间)")
     private String effectEndTime;
 
     /**
      * 备注
      */
-    @Column(name = "remark")
+    @TableField(value = "remark")
     @ApiModelProperty(value = "备注")
     private String remark;
 
     /**
      * 报警名称
      */
-    @Column(name = "name")
+    @TableField(value = "name")
     @ApiModelProperty(value = "报警名称")
     private String name;
 
     /**
      * 报警结束值
      */
+    @TableField(value = "end_info")
     @ApiModelProperty(value = "报警结束值")
     @JSONField(jsonDirect = true)
     private String endInfo;
 
     /**
-     * 有效期结束时间
+     * 有效期结束时间
      */
+    @TableField(value = "end_time")
     @ApiModelProperty(value = "报警自动过期时间")
     private Date endTime;
     /**
      * 报警名称
      */
-    @Column(name = "project_id")
+    @TableField(value = "project_id")
     @ApiModelProperty(value = "项目ID")
     private String projectId;
 

+ 13 - 6
src/main/java/com/persagy/job/AlarmExpireJob.java

@@ -9,8 +9,8 @@ import com.persagy.entity.AlarmRecord;
 import com.persagy.entity.AlarmState;
 import com.persagy.entity.NettyMessage;
 import com.persagy.entity.ZktAlarmRecordDO;
+import com.persagy.mapper.AlarmRecordMapper;
 import com.persagy.netty.client.NettyClient;
-import com.persagy.repository.AlarmRecordRepository;
 import com.persagy.utils.DateUtils;
 import com.persagy.utils.StringUtil;
 import lombok.extern.slf4j.Slf4j;
@@ -32,7 +32,7 @@ public class AlarmExpireJob extends QuartzJobBean {
 
     private final AtomicLong nums = new AtomicLong(1L);
     @Autowired
-    AlarmRecordRepository alarmRecordRepository;
+    AlarmRecordMapper alarmRecordMapper;
     @Autowired
     AlarmInfoCache alarmInfoCache;
     @Autowired
@@ -99,7 +99,11 @@ public class AlarmExpireJob extends QuartzJobBean {
             if (StringUtils.isNotBlank(alarmRecord)) {
                 ZktAlarmRecordDO zktAlarmRecordDO = StringUtil.tranferItemToDTO(alarmRecord, ZktAlarmRecordDO.class);
                 //立即过期,过期的时候可能还没有报警记录ID,需要重新执行下
-                String alarmId = alarmRecordRepository.findById(zktAlarmRecordDO.getDefinitionId()).orElse(new ZktAlarmRecordDO()).getAlarmId();
+                ZktAlarmRecordDO data = this.alarmRecordMapper.selectById(defineId);
+                if (null == data) {
+                    data = new ZktAlarmRecordDO();
+                }
+                String alarmId = data.getAlarmId();
                 if (StringUtil.isEmpty(alarmId)) {
                     log.info("refire:[{}]", refire);
                     mergedJobDataMap.put("refire", String.valueOf(StringUtil.getInt(refire) + 1));
@@ -120,7 +124,7 @@ public class AlarmExpireJob extends QuartzJobBean {
                     message.setEndInfo(endInfo);
                     message.setEndTime(DateUtils.parse(endTime));
                 }
-                if("3".equals(state)){
+                if ("3".equals(state)) {
                     message.setEndTime(DateUtils.parse(expireTime));
                 }
                 nettyMessage.setContent(Arrays.asList(message));
@@ -129,8 +133,11 @@ public class AlarmExpireJob extends QuartzJobBean {
                 //已经过期的时候删除掉这条报警定义了,保证不会再次产生报警
                 AlarmState alarmState = new AlarmState(defineId);
                 alarmInfoCache.setAlarmState(defineId, alarmState);
-                if (alarmRecordRepository.existsById(zktAlarmRecordDO.getDefinitionId())) {
-                    alarmRecordRepository.deleteById(zktAlarmRecordDO.getDefinitionId());
+//                if (alarmRecordRepository.existsById(zktAlarmRecordDO.getDefinitionId())) {
+//                    alarmRecordRepository.deleteById(zktAlarmRecordDO.getDefinitionId());
+//                }
+                if (null != this.alarmRecordMapper.selectById(zktAlarmRecordDO.getDefinitionId())) {
+                    this.alarmRecordMapper.deleteById(zktAlarmRecordDO.getDefinitionId());
                 }
             }
             log.info("----------------结束---------------------");

+ 24 - 21
src/main/java/com/persagy/kafka/KafkaConsumer.java

@@ -1,16 +1,6 @@
 package com.persagy.kafka;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Objects;
-import java.util.Optional;
-
-import org.apache.kafka.clients.consumer.ConsumerRecord;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
-import org.springframework.context.annotation.Configuration;
-import org.springframework.kafka.annotation.KafkaListener;
-import org.springframework.kafka.support.Acknowledgment;
 
+import cn.hutool.core.collection.CollectionUtil;
 import com.alibaba.fastjson.JSONObject;
 import com.alibaba.fastjson.TypeReference;
 import com.persagy.cache.AlarmInfoCache;
@@ -21,31 +11,41 @@ import com.persagy.entity.ZktAlarmRecordDO;
 import com.persagy.service.IAlarmRecordService;
 import com.persagy.utils.AlarmDefineUtil;
 import com.persagy.utils.LockUtil;
-
-import cn.hutool.core.collection.CollectionUtil;
 import lombok.extern.slf4j.Slf4j;
+import org.apache.kafka.clients.consumer.ConsumerRecord;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.kafka.annotation.KafkaListener;
+import org.springframework.kafka.support.Acknowledgment;
+
+import java.util.Iterator;
+import java.util.List;
+import java.util.Objects;
+import java.util.Optional;
 
 /**
  * kafak消费
+ *
  * @author 易涛
  * @version 1.0
  */
 @Configuration
 @Slf4j
-@ConditionalOnProperty(prefix = "spring.kafka",name = "enable",havingValue = "true")
+@ConditionalOnProperty(prefix = "spring.kafka", name = "enable", havingValue = "true")
 public class KafkaConsumer {
 
     @Autowired
     private IAlarmRecordService alarmRecordService;
 
     @KafkaListener(topics = {"#{'${topicName}'.split(',')}"}, containerFactory = "listenerContainerFactory")
-    public void topicCloudAlarmConsumer(List<ConsumerRecord<?,String>> record, Acknowledgment ack) {
+    public void topicCloudAlarmConsumer(List<ConsumerRecord<?, String>> record, Acknowledgment ack) {
         Iterator<ConsumerRecord<?, String>> it = record.iterator();
         while (it.hasNext()) {
             ConsumerRecord<?, String> consumerRecords = it.next();
             Optional<String> message = Optional.ofNullable(consumerRecords.value());
             if (message.isPresent()) {
-                NettyMessage msg = JSONObject.parseObject(message.get(),NettyMessage.class);
+                NettyMessage msg = JSONObject.parseObject(message.get(), NettyMessage.class);
                 try {
                     if (Objects.equals(msg.getProjectId(), CommonConst.projectId)) {
                         handlerMsg(msg);
@@ -60,12 +60,12 @@ public class KafkaConsumer {
 
     private void handlerMsg(NettyMessage msg) {
         if (msg.getOpCode() == 7) {
-            log.info("--报警定义新增或更新--{}",msg);
+            log.info("--报警定义新增或更新--{}", msg);
             NettyMessage<AlarmDefine> alarmDefineMessage = JSONObject.parseObject(msg.toString(), new TypeReference<NettyMessage<AlarmDefine>>() {
             });
             List<AlarmDefine> definesList = alarmDefineMessage.getContent();
             if (CollectionUtil.isNotEmpty(definesList)) {
-            	AlarmDefineUtil.listSomeAlarmDefine(definesList);
+                AlarmDefineUtil.listSomeAlarmDefine(definesList);
             }
         } else if (msg.getOpCode() == 8) {
             log.info("-----报警记录id推送----[{}]", msg);
@@ -74,11 +74,13 @@ public class KafkaConsumer {
                 JSONObject parseObject = JSONObject.parseObject(JSONObject.toJSONString(content.get(0)));
                 String defineId = AlarmInfoCache.getAlarmDefineId(parseObject);
                 ZktAlarmRecordDO zktAlarmRecordDO = alarmRecordService.findById(defineId).orElse(new ZktAlarmRecordDO());
+                log.debug("-----查询的结果----[{}]", JSONObject.toJSONString(zktAlarmRecordDO));
                 zktAlarmRecordDO.setDefinitionId(defineId);
                 zktAlarmRecordDO.setObjId(parseObject.getString("objId"));
                 zktAlarmRecordDO.setItemId(parseObject.getString("itemId"));
                 zktAlarmRecordDO.setAlarmId(parseObject.getString("id"));
-                alarmRecordService.save(zktAlarmRecordDO);
+                log.debug("-----要保存的值----[{}]", JSONObject.toJSONString(zktAlarmRecordDO));
+                alarmRecordService.replaceSave(zktAlarmRecordDO);
             }
         } else if (msg.getOpCode() == 9) {
             NettyMessage<AlarmDefine> alarmDefineMessage = JSONObject.parseObject(msg.toString(), new TypeReference<NettyMessage<AlarmDefine>>() {
@@ -104,7 +106,7 @@ public class KafkaConsumer {
             });
             List<AlarmDefine> definesList = alarmDefineMessage.getContent();
             if (CollectionUtil.isNotEmpty(definesList)) {
-            	AlarmDefineUtil.deleteAlarmDefine(definesList);
+                AlarmDefineUtil.deleteAlarmDefine(definesList);
             }
         } else if (msg.getOpCode() == 11) {
             //更新隔离的系统对象
@@ -116,7 +118,8 @@ public class KafkaConsumer {
             }
         } else if (msg.getOpCode() == 12) {
             //云端更新报警记录状态
-            NettyMessage<JSONObject> alarmDefineMessage = JSONObject.parseObject(msg.toString(), new TypeReference<NettyMessage<JSONObject>>() {});
+            NettyMessage<JSONObject> alarmDefineMessage = JSONObject.parseObject(msg.toString(), new TypeReference<NettyMessage<JSONObject>>() {
+            });
             List<JSONObject> stateList = alarmDefineMessage.getContent();
             alarmRecordService.updateAlarmDefine(stateList);
         }

+ 26 - 0
src/main/java/com/persagy/mapper/AlarmRecordMapper.java

@@ -0,0 +1,26 @@
+package com.persagy.mapper;
+
+import com.baomidou.mybatisplus.core.mapper.BaseMapper;
+import com.persagy.entity.ZktAlarmRecordDO;
+import org.apache.ibatis.annotations.Param;
+import org.apache.ibatis.annotations.Select;
+import org.apache.ibatis.annotations.Update;
+import org.mapstruct.Mapper;
+import org.springframework.stereotype.Repository;
+
+/**
+ * @description:
+ * @author: YangWanYi
+ * @create: 2022-07-22 16:58
+ **/
+@Mapper
+public interface AlarmRecordMapper extends BaseMapper<ZktAlarmRecordDO> {
+
+    @Update(value = "REPLACE INTO zkt_alarm_record ( DEFINITION_ID, PROJECT_ID, obj_id, ITEM_CODE, state, alarm_id, alarm_time, effect_end_time, remark, name, end_info, end_time, ITEM_ID )" +
+            " VALUES ( #{record.definitionId}, #{record.projectId}, #{record.objId}, #{record.itemCode}, #{record.state}, #{record.alarmId}, #{record.alarmTime}, #{record.effectEndTime}," +
+            " #{record.remark}, #{record.name}, #{record.endInfo}, #{record.endTime}, #{record.itemId} )")
+    int replaceSave(@Param("record") ZktAlarmRecordDO zktAlarmRecordDO);
+
+    @Select(value = "SELECT * FROM zkt_alarm_record a WHERE a.item_code = #{itemCode} and a.obj_id = #{objId}")
+    ZktAlarmRecordDO findByItemCodeAndObjId(@Param("itemCode") String itemCode, @Param("objId") String objId);
+}

+ 0 - 17
src/main/java/com/persagy/repository/AlarmRecordRepository.java

@@ -1,17 +0,0 @@
-package com.persagy.repository;
-
-import com.persagy.entity.ZktAlarmRecordDO;
-import org.springframework.data.jpa.repository.Query;
-import org.springframework.data.repository.PagingAndSortingRepository;
-import org.springframework.data.repository.query.Param;
-import org.springframework.stereotype.Repository;
-
-@Repository
-public interface AlarmRecordRepository extends PagingAndSortingRepository<ZktAlarmRecordDO, String> {
-
-
-    @Query(value = "SELECT * FROM zkt_alarm_record a WHERE a.item_code = :itemCode and a.obj_id = :objId", nativeQuery = true)
-    ZktAlarmRecordDO findByItemCodeAndObjId(@Param("itemCode") String itemCode, @Param("objId") String objId);
-
-
-}

+ 4 - 1
src/main/java/com/persagy/service/IAlarmRecordService.java

@@ -20,5 +20,8 @@ public interface IAlarmRecordService {
 	void save(ZktAlarmRecordDO zktAlarmRecordDO);
 
 	Optional<ZktAlarmRecordDO> findById(String defineId);
-	
+
+	int replaceSave(ZktAlarmRecordDO zktAlarmRecordDO);
+
+	ZktAlarmRecordDO findByItemCodeAndObjId(String qiangji1, String eq5001120003000a592ce6d34f79acf610c15777a9eb);
 }

+ 43 - 46
src/main/java/com/persagy/service/impl/AlarmHandleServiceImpl.java

@@ -1,49 +1,36 @@
 package com.persagy.service.impl;
 
-import static org.apache.commons.lang3.math.NumberUtils.INTEGER_ONE;
-
-import java.time.LocalDate;
-import java.time.LocalDateTime;
-import java.time.LocalTime;
-import java.time.format.DateTimeFormatter;
-import java.util.Arrays;
-import java.util.Date;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Objects;
-import java.util.Optional;
-
-import org.apache.commons.lang3.StringUtils;
-import org.quartz.JobDataMap;
-import org.quartz.SchedulerException;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.stereotype.Service;
-
+import cn.hutool.core.date.DateUtil;
+import cn.hutool.core.util.ObjectUtil;
+import cn.hutool.core.util.StrUtil;
 import com.alibaba.fastjson.JSONObject;
 import com.googlecode.aviator.AviatorEvaluator;
 import com.googlecode.aviator.Expression;
 import com.persagy.cache.AlarmInfoCache;
 import com.persagy.cache.CurrentDataCache;
 import com.persagy.constant.CommonConst;
-import com.persagy.entity.AlarmDefine;
-import com.persagy.entity.AlarmRecord;
-import com.persagy.entity.AlarmState;
-import com.persagy.entity.Condition;
-import com.persagy.entity.ExpireAlarmMessage;
-import com.persagy.entity.NettyMessage;
-import com.persagy.entity.ZktAlarmRecordDO;
+import com.persagy.entity.*;
 import com.persagy.job.ExpireAlarmQueue;
+import com.persagy.mapper.AlarmRecordMapper;
 import com.persagy.netty.client.NettyClient;
-import com.persagy.repository.AlarmRecordRepository;
 import com.persagy.service.AlarmHandleService;
 import com.persagy.service.AlarmQuartzService;
 import com.persagy.utils.DateUtils;
 import com.persagy.utils.StringUtil;
-
-import cn.hutool.core.date.DateUtil;
-import cn.hutool.core.util.ObjectUtil;
-import cn.hutool.core.util.StrUtil;
 import lombok.extern.slf4j.Slf4j;
+import org.apache.commons.lang3.StringUtils;
+import org.quartz.JobDataMap;
+import org.quartz.SchedulerException;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Service;
+
+import java.time.LocalDate;
+import java.time.LocalDateTime;
+import java.time.LocalTime;
+import java.time.format.DateTimeFormatter;
+import java.util.*;
+
+import static org.apache.commons.lang3.math.NumberUtils.INTEGER_ONE;
 
 /**
  * @description:报警处理实现类:包含报警产生和报警恢复
@@ -62,8 +49,7 @@ public class AlarmHandleServiceImpl implements AlarmHandleService {
     @Autowired
     AlarmQuartzService alarmQuartzService;
     @Autowired
-    AlarmRecordRepository alarmRecordRepository;
-
+    AlarmRecordMapper alarmRecordMapper;
 
     /**
      * @param msg:
@@ -77,11 +63,11 @@ public class AlarmHandleServiceImpl implements AlarmHandleService {
      */
     @Override
     public void handleIOTData(String msg) throws SchedulerException, InterruptedException {
-		JSONObject parseObject = JSONObject.parseObject(msg);
-		msg = parseObject.getString("data");
-		if (StrUtil.isBlank(msg)) {
-			return;
-		}
+        JSONObject parseObject = JSONObject.parseObject(msg);
+        msg = parseObject.getString("data");
+        if (StrUtil.isBlank(msg)) {
+            return;
+        }
         String[] split = msg.split(";", -1);
         if (split.length % 4 != 0) {
             return;
@@ -94,11 +80,11 @@ public class AlarmHandleServiceImpl implements AlarmHandleService {
             String funcId = split[i * 4 + 2];
             String valueStr = split[i * 4 + 3];
             if (StrUtil.isNotBlank(valueStr) || "null".equalsIgnoreCase(valueStr)) {
-            	double value = Double.parseDouble(valueStr);
+                double value = Double.parseDouble(valueStr);
                 if (AlarmInfoCache.hasKey(meterId, funcId)) {
                     validIotData(dateTime, meterId, funcId, value);
                 }
-			}
+            }
         }
     }
 
@@ -137,7 +123,7 @@ public class AlarmHandleServiceImpl implements AlarmHandleService {
                     if (Objects.isNull(alarmState)) {
                         //默认正常报警状态
                         alarmState = new AlarmState(defineId);
-                        Optional<ZktAlarmRecordDO> recordOptional = alarmRecordRepository.findById(defineId);
+                        Optional<ZktAlarmRecordDO> recordOptional = Optional.ofNullable(this.alarmRecordMapper.selectById(defineId));
                         if (recordOptional.isPresent()) {
                             ZktAlarmRecordDO alarmRecordDO = recordOptional.get();
                             //数据库报警状态:1-未处理
@@ -217,7 +203,10 @@ public class AlarmHandleServiceImpl implements AlarmHandleService {
             if (DateUtils.betweenTwoTimeSecond(endTime, dateTime) >= uphold) {
                 log.info("产生一条报警恢复消息[{}]>[{}]", DateUtils.betweenTwoTimeSecond(endTime, dateTime), uphold);
                 NettyMessage<AlarmRecord> nettyMessage = new NettyMessage<>(6);
-                ZktAlarmRecordDO alarmRecordDO = alarmRecordRepository.findById(AlarmInfoCache.getAlarmDefineId(alarmDefine)).orElse(new ZktAlarmRecordDO());
+                ZktAlarmRecordDO alarmRecordDO = this.alarmRecordMapper.selectById(defineId);
+                if (null == alarmRecordDO) {
+                    alarmRecordDO = new ZktAlarmRecordDO();
+                }
                 alarmRecordDO.setDefinitionId(defineId);
                 alarmRecordDO.setObjId(alarmDefine.getObjId());
                 alarmRecordDO.setItemCode(alarmDefine.getItemCode());
@@ -226,7 +215,7 @@ public class AlarmHandleServiceImpl implements AlarmHandleService {
                 alarmRecordDO.setEndTime(DateUtils.parseDate(dateTime));
                 alarmRecordDO.setEndInfo(JSONObject.toJSONString(paramMap));
                 //更新报警状态
-                alarmRecordRepository.save(alarmRecordDO);
+                this.alarmRecordMapper.replaceSave(alarmRecordDO);
                 String alarmId = alarmRecordDO.getAlarmId();
                 //报警恢复参数
                 AlarmRecord alarmResumeRecord = AlarmRecord.builder()
@@ -395,7 +384,11 @@ public class AlarmHandleServiceImpl implements AlarmHandleService {
             nettyMessage.setContent(Arrays.asList(alarmRecord));
             //推送一条报警记录给远端
             nettyClient.sendMessage(nettyMessage);
-            ZktAlarmRecordDO zktAlarmRecordDO = alarmRecordRepository.findById(defineId).orElse(new ZktAlarmRecordDO());
+//            ZktAlarmRecordDO zktAlarmRecordDO = alarmRecordRepository.findById(defineId).orElse(new ZktAlarmRecordDO());
+            ZktAlarmRecordDO zktAlarmRecordDO = this.alarmRecordMapper.selectById(defineId);
+            if (null == zktAlarmRecordDO) {
+                zktAlarmRecordDO = new ZktAlarmRecordDO();
+            }
             zktAlarmRecordDO.setDefinitionId(defineId);
             zktAlarmRecordDO.setObjId(alarmDefine.getObjId());
             zktAlarmRecordDO.setItemCode(alarmDefine.getItemCode());
@@ -403,13 +396,17 @@ public class AlarmHandleServiceImpl implements AlarmHandleService {
             zktAlarmRecordDO.setState(AlarmState.State.NOT_DEAL.getType());
             zktAlarmRecordDO.setAlarmTime(alarmState.getAlarmStartTime());
             zktAlarmRecordDO.setProjectId(alarmDefine.getProjectId());
-            alarmRecordRepository.save(zktAlarmRecordDO);
+            this.alarmRecordMapper.replaceSave(zktAlarmRecordDO);
             alarmState.setState(AlarmState.State.NOT_DEAL.getType());
             //有过期时间,生成报警过期消息
             if (hasExpire && "period".equals(effectTime.getString("type"))) {
                 //过期时间
                 log.error("产生一条定时过期报警消息");
-                String alarmId = alarmRecordRepository.findById(defineId).orElse(new ZktAlarmRecordDO()).getAlarmId();
+                ZktAlarmRecordDO data = this.alarmRecordMapper.selectById(defineId);
+                if (null == data) {
+                    data = new ZktAlarmRecordDO();
+                }
+                String alarmId = data.getAlarmId();
                 ZktAlarmRecordDO alarmRecordDO = ZktAlarmRecordDO.builder()
                         .alarmTime(alarmState.getAlarmStartTime())
                         .effectEndTime(DateUtils.format(expireDateTime))

+ 43 - 30
src/main/java/com/persagy/service/impl/AlarmRecordService.java

@@ -1,38 +1,37 @@
 package com.persagy.service.impl;
 
-import java.util.List;
-import java.util.Optional;
-
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.stereotype.Service;
-
+import cn.hutool.core.collection.CollectionUtil;
 import com.alibaba.fastjson.JSONObject;
 import com.persagy.cache.AlarmInfoCache;
 import com.persagy.entity.AlarmState;
 import com.persagy.entity.ExpireAlarmMessage;
 import com.persagy.entity.ZktAlarmRecordDO;
 import com.persagy.job.ExpireAlarmQueue;
-import com.persagy.repository.AlarmRecordRepository;
+import com.persagy.mapper.AlarmRecordMapper;
 import com.persagy.service.IAlarmRecordService;
-
-import cn.hutool.core.collection.CollectionUtil;
 import lombok.extern.slf4j.Slf4j;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+
+import java.util.List;
+import java.util.Optional;
 
 /**
- * 
- * @version 1.0.0
- * @company persagy 
  * @author zhangqiankun
+ * @version 1.0.0
+ * @company persagy
  * @date 2022年2月18日 上午10:06:54
  */
 @Slf4j
 @Service
 public class AlarmRecordService implements IAlarmRecordService {
 
-	@Autowired
-    private AlarmRecordRepository alarmRecordRepository;
-	
-	@Override
+
+    @Autowired
+    AlarmRecordMapper alarmRecordMapper;
+
+    @Override
     public void updateAlarmDefine(List<JSONObject> alarmDefineList) {
         if (CollectionUtil.isNotEmpty(alarmDefineList)) {
             for (JSONObject stateItem : alarmDefineList) {
@@ -44,15 +43,18 @@ public class AlarmRecordService implements IAlarmRecordService {
                 String newState = "1".equals(state) ? "1" : "0";
                 alarmState.setState(newState);
                 AlarmInfoCache.setAlarmState(defineId, alarmState);
-                ZktAlarmRecordDO zktAlarmRecordDO = alarmRecordRepository.findById(defineId).orElse(new ZktAlarmRecordDO());
+                ZktAlarmRecordDO zktAlarmRecordDO = this.alarmRecordMapper.selectById(defineId);
+                if (null == zktAlarmRecordDO) {
+                    zktAlarmRecordDO = new ZktAlarmRecordDO();
+                }
                 zktAlarmRecordDO.setDefinitionId(defineId);
                 zktAlarmRecordDO.setProjectId(stateItem.getString("projectId"));
                 zktAlarmRecordDO.setObjId(stateItem.getString("objId"));
                 zktAlarmRecordDO.setItemCode(stateItem.getString("itemCode"));
                 zktAlarmRecordDO.setItemId(stateItem.getString("itemId"));
                 zktAlarmRecordDO.setState(stateItem.getString("state"));
-                alarmRecordRepository.save(zktAlarmRecordDO);
-                if("2".equals(state)||"3".equals(state)) {
+                this.alarmRecordMapper.replaceSave(zktAlarmRecordDO);
+                if ("2".equals(state) || "3".equals(state)) {
                     try {
                         ExpireAlarmMessage em = new ExpireAlarmMessage();
                         //取消过期消息
@@ -62,22 +64,33 @@ public class AlarmRecordService implements IAlarmRecordService {
                         ExpireAlarmQueue.getExpireAlarmMessageQueue().produce(em);
                         //报警恢复,报警状态重置回默认
                         alarmState.reset();
-                    }catch (Exception e){
-                        log.error("取消过期定时任务失败",e);
+                    } catch (Exception e) {
+                        log.error("取消过期定时任务失败", e);
                     }
                 }
             }
         }
     }
 
-	@Override
-	public void save(ZktAlarmRecordDO zktAlarmRecordDO) {
-		this.alarmRecordRepository.save(zktAlarmRecordDO);
-	}
+    @Override
+    public void save(ZktAlarmRecordDO zktAlarmRecordDO) {
+        this.alarmRecordMapper.replaceSave(zktAlarmRecordDO);
+    }
+
+    @Override
+    public Optional<ZktAlarmRecordDO> findById(String defineId) {
+        return Optional.ofNullable(this.alarmRecordMapper.selectById(defineId));
+    }
+
+    @Override
+    @Transactional
+    public int replaceSave(ZktAlarmRecordDO zktAlarmRecordDO) {
+        return this.alarmRecordMapper.replaceSave(zktAlarmRecordDO);
+    }
+
+    @Override
+    public ZktAlarmRecordDO findByItemCodeAndObjId(String itemCode, String objId) {
+        return this.alarmRecordMapper.findByItemCodeAndObjId(itemCode, objId);
+    }
 
-	@Override
-	public Optional<ZktAlarmRecordDO> findById(String defineId) {
-		return this.alarmRecordRepository.findById(defineId);
-	}
-	
 }