第6天

完成了安全检查表基本的增删改查,和安全风险表,风险历史表的创建
今天完成批量导出的demo了
完成员工记录表,员工记录历史表,风险检查表的增删改查。
再然后是批量导入 原来做批量导出的使用了之前教程里的文件操作,过于繁琐 后来结合ai和博客,实现文件导入
部分代码:
package com.example.springbootdemo.repository;
import com.example.springbootdemo.entity.SafetyRiskHistory;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;

import java.util.Date;
import java.util.List;

@Repository
public interface SafetyRiskHistoryRepository extends JpaRepository<SafetyRiskHistory, Integer> {

// 使用 @Query 注解自定义查询
@Query("SELECT srh FROM SafetyRiskHistory srh WHERE srh.risk_code = :riskCode")
List<SafetyRiskHistory> findByRiskCode(String riskCode);
@Query("SELECT srh FROM SafetyRiskHistory srh " +
        "WHERE (:riskCode IS NULL OR srh.risk_code = :riskCode) " +
        "AND (:startDate IS NULL OR srh.operation_time >= :startDate) " +
        "AND (:endDate IS NULL OR srh.operation_time <= :endDate)")
Page<SafetyRiskHistory> findByRiskCodeAndTimeRange(String riskCode, Date startDate, Date endDate, Pageable pageable);

}
package com.example.springbootdemo.service;

import com.example.springbootdemo.entity.SafetyRiskHistory;
import com.example.springbootdemo.entity.safetyrisk;
import com.example.springbootdemo.repository.SafetyRiskHistoryRepository;
import com.example.springbootdemo.repository.SafetyriskRepository;
import jakarta.persistence.EntityManager;
import jakarta.persistence.PersistenceContext;
import jakarta.transaction.Transactional;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Optional;

@Service
public class SafetyRiskService {
@PersistenceContext
private EntityManager entityManager;

@Autowired
private SafetyriskRepository safetyRiskRepository;

@Autowired
private SafetyRiskHistoryRepository safetyRiskHistoryRepository;

public safetyrisk saveSafetyRisk(safetyrisk safetyRisk, String operator) {
    if (safetyRisk.getId() == null) {
        // 新增操作
        safetyrisk savedRisk = safetyRiskRepository.save(safetyRisk);
        saveRiskHistory(savedRisk, 1, "增加", operator);
        return savedRisk;
    } else {
        // 更新操作
        Optional<safetyrisk> optionalRisk = safetyRiskRepository.findById(safetyRisk.getId());
        if (optionalRisk.isPresent()) {
            safetyrisk existingRisk = optionalRisk.get();
            // 使用 BeanUtils 复制属性,排除 ID 字段
            BeanUtils.copyProperties(safetyRisk, existingRisk, "id");

            safetyrisk updatedRisk = safetyRiskRepository.save(existingRisk);
            // 获取当前最大版本号
            Integer maxVersion = getMaxVersion(updatedRisk.getRisk_code());
            saveRiskHistory(updatedRisk, maxVersion + 1, "更新", operator);
            return updatedRisk;
        } else {
            // 若记录不存在,可以选择抛出异常或者返回 null
            System.out.println("未找到 ID 为 " + safetyRisk.getId() + " 的记录,无法更新。");
            return null;
        }
    }
}

public Page<safetyrisk> getAllSafetyRisks(int page, int size) {
    Pageable pageable = PageRequest.of(page - 1, size);
    System.out.println("获取所有风险数据,页码: " + page + ", 每页数量: " + size);
    Page<safetyrisk> result = safetyRiskRepository.findAll(pageable);
    System.out.println("查询结果数量: " + result.getTotalElements());
    return result;
}

public void deleteSafetyRisk(int id, String operator) {
    Optional<safetyrisk> optionalRisk = safetyRiskRepository.findById(id);
    if (optionalRisk.isPresent()) {
        safetyrisk risk = optionalRisk.get();
        // 获取当前最大版本号
        Integer maxVersion = getMaxVersion(risk.getRisk_code());
        saveRiskHistory(risk, maxVersion + 1, "删除", operator);
        safetyRiskRepository.deleteById(id);
    }
}

public Page<safetyrisk> getSafetyRisksByQuery(
        Integer id,
        String riskCode,
        String department,
        String professionalSystem,
        String riskCategory,
        String riskItem,
        String riskPoint,
        String riskLevel,
        String harmDegree,
        String controlMeasures,
        String controlPosition,
        String controlPersonnel,
        String quantifiedRequirements,
        Date entryStartDate,
        Date entryEndDate,
        String reviewStatus,
        Date reviewDate,
        int page,
        int size
) {
    Pageable pageable = PageRequest.of(page - 1, size);
    System.out.println("查询条件: id=" + id + ", riskCode=" + riskCode + ", department=" + department +
            ", professionalSystem=" + professionalSystem + ", riskCategory=" + riskCategory +
            ", riskItem=" + riskItem + ", riskPoint=" + riskPoint + ", riskLevel=" + riskLevel +
            ", harmDegree=" + harmDegree + ", controlMeasures=" + controlMeasures +
            ", controlPosition=" + controlPosition + ", controlPersonnel=" + controlPersonnel +
            ", quantifiedRequirements=" + quantifiedRequirements + ", entryStartDate=" + entryStartDate +
            ", entryEndDate=" + entryEndDate + ", reviewStatus=" + reviewStatus +
            ", reviewDate=" + reviewDate + ", 页码: " + page + ", 每页数量: " + size);
    Page<safetyrisk> result = safetyRiskRepository.findByMultipleConditions(
            id, riskCode, department, professionalSystem, riskCategory,
            riskItem, riskPoint, riskLevel, harmDegree, controlMeasures,
            controlPosition, controlPersonnel, quantifiedRequirements,
            entryStartDate, entryEndDate, reviewStatus, reviewDate,
            pageable
    );
    System.out.println("查询结果数量: " + result.getTotalElements());
    return result;
}

public List<safetyrisk> list() {
    return safetyRiskRepository.findAll();
}

@Transactional
public void saveBatch(List<safetyrisk> riskList, String operator) {
    try {
        for (safetyrisk risk : riskList) {
            saveSafetyRisk(risk, operator);
        }
    } catch (Exception e) {
        System.out.println("数据批量保存失败:" + e.getMessage());
        e.printStackTrace();
        throw new RuntimeException("数据批量保存失败", e);
    }
}

public List<safetyrisk> findByRiskCode(String riskCode) {
    return safetyRiskRepository.findByRiskCode(riskCode);
}

// 保存安全风险历史记录
private void saveRiskHistory(safetyrisk risk, Integer version, String operationType, String operator) {
    SafetyRiskHistory history = new SafetyRiskHistory();
    // 使用 BeanUtils 复制属性
    BeanUtils.copyProperties(risk, history);
    history.setId(null); // 确保每次保存的是新实体

    history.setVersion(version);
    history.setOperation_type(operationType);
    history.setOperation_time(new Date());
    history.setPerson(operator); // 设置操作人信息

    safetyRiskHistoryRepository.save(history);
}

// 获取指定风险编码的最大版本号
private Integer getMaxVersion(String riskCode) {
    List<SafetyRiskHistory> histories = safetyRiskHistoryRepository.findByRiskCode(riskCode);
    if (histories.isEmpty()) {
        return 0;
    }
    return histories.stream()
            .mapToInt(SafetyRiskHistory::getVersion)
            .max()
            .orElse(0);
}

public Page<SafetyRiskHistory> getRiskHistoryByQuery(String riskCode, Date startDate, Date endDate, Pageable pageable) {
    return safetyRiskHistoryRepository.findByRiskCodeAndTimeRange(riskCode, startDate, endDate, pageable);
}

}

posted @ 2025-04-26 10:55  深度检测  阅读(35)  评论(0)    收藏  举报