学习进度条

学习时间:1小时
代码量:100行
博客产出:1篇
核心知识点:团队项目,设备检测计划的相关增删改查
实体类DetectionPlan.java

package com.example.littlebabydemo0425.pojo;

import jakarta.persistence.*;
import java.util.Date;

@Entity
@Table(name = "detection_plan", indexes = {
        @Index(name = "idx_device_type", columnList = "device_type"),
        @Index(name = "idx_status", columnList = "status")
})
public class DetectionPlan {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(name = "plan_code", length = 64, nullable = false)
    private String planCode;

    @Column(name = "plan_name", length = 128, nullable = false)
    private String planName;

    @Column(name = "device_type", length = 32, nullable = false)
    private String deviceType;

    @Column(name = "start_time", nullable = false)
    private Date startTime;

    @Column(name = "end_time", nullable = false)
    private Date endTime;

    @Column(name = "frequency", length = 16, nullable = false)
    private String frequency;

    @Column(name = "duration")
    private Integer duration;

    @Column(name = "min_stay_time", columnDefinition = "int default 2")
    private Integer minStayTime;

    @Column(name = "status", columnDefinition = "tinyint default 1")
    private Integer status;

    @Column(name = "create_time", columnDefinition = "datetime default CURRENT_TIMESTAMP")
    private Date createTime;

    @Column(name = "update_time", columnDefinition = "datetime default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP")
    private Date updateTime;

    // Getters and Setters
    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getPlanCode() {
        return planCode;
    }

    public void setPlanCode(String planCode) {
        this.planCode = planCode;
    }

    public String getPlanName() {
        return planName;
    }

    public void setPlanName(String planName) {
        this.planName = planName;
    }

    public String getDeviceType() {
        return deviceType;
    }

    public void setDeviceType(String deviceType) {
        this.deviceType = deviceType;
    }

    public Date getStartTime() {
        return startTime;
    }

    public void setStartTime(Date startTime) {
        this.startTime = startTime;
    }

    public Date getEndTime() {
        return endTime;
    }

    public void setEndTime(Date endTime) {
        this.endTime = endTime;
    }

    public String getFrequency() {
        return frequency;
    }

    public void setFrequency(String frequency) {
        this.frequency = frequency;
    }

    public Integer getDuration() {
        return duration;
    }

    public void setDuration(Integer duration) {
        this.duration = duration;
    }

    public Integer getMinStayTime() {
        return minStayTime;
    }

    public void setMinStayTime(Integer minStayTime) {
        this.minStayTime = minStayTime;
    }

    public Integer getStatus() {
        return status;
    }

    public void setStatus(Integer status) {
        this.status = status;
    }

    public Date getCreateTime() {
        return createTime;
    }

    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }

    public Date getUpdateTime() {
        return updateTime;
    }

    public void setUpdateTime(Date updateTime) {
        this.updateTime = updateTime;
    }
}

controller层代码

package com.example.littlebabydemo0425.controller;


import com.example.littlebabydemo0425.mapper.DetectionPlanMapper;
import com.example.littlebabydemo0425.pojo.DetectionPlan;
import com.example.littlebabydemo0425.pojo.PageBean;
import com.example.littlebabydemo0425.pojo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;


@RestController
@RequestMapping("/api/detection-plans/")
@CrossOrigin(origins = "http://localhost:5173") // 添加CORS支持
public class DetectionPlansController {
    @Autowired
    private DetectionPlanMapper detectionPlanMapper;

    @GetMapping
    public Result<PageBean<DetectionPlan>> getDetectionPlans(Integer pageNum,
                                                             Integer pageSize,
                                                             @RequestParam(required = false)String deviceType,
                                                             @RequestParam(required = false)String planName,
                                                             @RequestParam(required = false) String status) {
        PageBean<DetectionPlan> pageBean = detectionPlanMapper.getDetectionPlans(pageNum,pageSize,deviceType,planName,status);
        return Result.success(pageBean);
    }
    // 新增检测计划的方法
    @PostMapping
    @Transactional // 添加事务注解
    public Result<DetectionPlan> addDetectionPlan(@RequestBody DetectionPlan detectionPlan) {
        try {
            // 验证必要字段
            if (detectionPlan.getPlanName() == null || detectionPlan.getDeviceType() == null) {
                return Result.error("计划名称和设备类型不能为空");
            }

            // 调用mapper层的插入方法
            int rowsInserted = detectionPlanMapper.insert(detectionPlan);
            if (rowsInserted > 0) {
                // 插入成功,返回成功的结果和插入的检测计划对象
                return Result.success(detectionPlan);
            } else {
                // 插入失败,返回失败的结果
                return Result.error("添加检测计划失败");
            }
        } catch (Exception e) {
            // 捕获异常,返回失败的结果
            e.printStackTrace();
            return Result.error("添加检测计划时发生异常: " + e.getMessage());
        }
    }
}

mapper层代码(包括分页查询跟条件查询)

package com.example.littlebabydemo0425.mapper;

import com.example.littlebabydemo0425.pojo.DetectionPlan;
import com.example.littlebabydemo0425.pojo.PageBean;
import org.apache.ibatis.annotations.*;
import org.apache.ibatis.jdbc.SQL;

import java.util.List;

@Mapper
public interface DetectionPlanMapper {

    // 新增检测计划
    @Insert("INSERT INTO detection_plan(plan_code, plan_name, device_type, start_time, " +
            "end_time, frequency, duration, min_stay_time, status) " +
            "VALUES(#{planCode}, #{planName}, #{deviceType}, #{startTime}, " +
            "#{endTime}, #{frequency}, #{duration}, #{minStayTime}, #{status})")
    @Options(useGeneratedKeys = true, keyProperty = "id")
    int insert(DetectionPlan detectionPlan);

    // 根据ID删除检测计划
    @Delete("DELETE FROM detection_plan WHERE id = #{id}")
    int deleteById(Long id);

    // 更新检测计划
    @Update("UPDATE detection_plan SET " +
            "plan_code = #{planCode}, " +
            "plan_name = #{planName}, " +
            "device_type = #{deviceType}, " +
            "start_time = #{startTime}, " +
            "end_time = #{endTime}, " +
            "frequency = #{frequency}, " +
            "duration = #{duration}, " +
            "min_stay_time = #{minStayTime}, " +
            "status = #{status} " +
            "WHERE id = #{id}")
    int update(DetectionPlan detectionPlan);

    // 根据ID查询检测计划
    @Select("SELECT * FROM detection_plan WHERE id = #{id}")
    DetectionPlan selectById(Long id);

    // 查询所有检测计划
    @Select("SELECT * FROM detection_plan")
    List<DetectionPlan> selectAll();

    // 根据设备类型查询检测计划
    @Select("SELECT * FROM detection_plan WHERE device_type = #{deviceType}")
    List<DetectionPlan> selectByDeviceType(String deviceType);

    // 根据状态查询检测计划
    @Select("SELECT * FROM detection_plan WHERE status = #{status}")
    List<DetectionPlan> selectByStatus(Integer status);

    // 更新计划状态
    @Update("UPDATE detection_plan SET status = #{status} WHERE id = #{id}")
    int updateStatus(@Param("id") Long id, @Param("status") Integer status);

    // 根据计划编号查询
    @Select("SELECT * FROM detection_plan WHERE plan_code = #{planCode}")
    DetectionPlan selectByPlanCode(String planCode);

    // 分页查询检测计划
    @Select("SELECT * FROM detection_plan LIMIT #{offset}, #{pageSize}")
    List<DetectionPlan> selectByPage(@Param("offset") Integer offset,
                                     @Param("pageSize") Integer pageSize);

    // 统计检测计划数量
    @Select("SELECT COUNT(*) FROM detection_plan")
    int count();

    /**
     * 分页查询检测计划列表
     * @param pageNum 页码
     * @param pageSize 每页大小
     * @param deviceType 设备类型(可选)
     * @param planName 计划名称(可选)
     * @param status 计划状态(可选)
     * @return 分页结果
     */
    default PageBean<DetectionPlan> getDetectionPlans(Integer pageNum, Integer pageSize, String deviceType, String planName, String status) {
        PageBean<DetectionPlan> pb = new PageBean<>();

        // 计算偏移量
        int offset = (pageNum - 1) * pageSize;

        // 查询数据
        List<DetectionPlan> detectionPlans = selectByCondition(deviceType, planName, status, offset, pageSize);
        pb.setItems(detectionPlans);

        // 查询总数
        long total = countByCondition(deviceType, planName, status);
        pb.setTotal(total);

        return pb;
    }

    @SelectProvider(type = DetectionPlanSqlProvider.class, method = "selectByCondition")
    List<DetectionPlan> selectByCondition(
            @Param("deviceType") String deviceType,
            @Param("planName") String planName,
            @Param("status") String status,
            @Param("offset") int offset,
            @Param("pageSize") int pageSize);

    @SelectProvider(type = DetectionPlanSqlProvider.class, method = "countByCondition")
    long countByCondition(
            @Param("deviceType") String deviceType,
            @Param("planName") String planName,
            @Param("status") String status);

    // SQL提供类
    class DetectionPlanSqlProvider {
        public String selectByCondition(
                @Param("deviceType") String deviceType,
                @Param("planName") String planName,
                @Param("status") String status,
                @Param("offset") int offset,
                @Param("pageSize") int pageSize) {
            return new SQL() {{
                SELECT("*");
                FROM("detection_plan");
                if (deviceType != null && !deviceType.isEmpty()) {
                    WHERE("device_type LIKE CONCAT('%', #{deviceType}, '%')");
                }
                if (planName != null && !planName.isEmpty()) {
                    WHERE("plan_name LIKE CONCAT('%', #{planName}, '%')");
                }
                if (status != null && !status.isEmpty()) {
                    WHERE("status = #{status}");
                }
                ORDER_BY("id DESC");
            }}.toString() + " LIMIT #{offset}, #{pageSize}";
        }

        public String countByCondition(
                @Param("deviceType") String deviceType,
                @Param("planName") String planName,
                @Param("status") String status) {
            return new SQL() {{
                SELECT("COUNT(*)");
                FROM("detection_plan");
                if (deviceType != null && !deviceType.isEmpty()) {
                    WHERE("device_type LIKE CONCAT('%', #{deviceType}, '%')");
                }
                if (planName != null && !planName.isEmpty()) {
                    WHERE("plan_name LIKE CONCAT('%', #{planName}, '%')");
                }
                if (status != null && !status.isEmpty()) {
                    WHERE("status = #{status}");
                }
            }}.toString();
        }
    }
}

以上代码完成检测计划的列表显示,分页查询以及条件查询功能

posted @ 2025-04-25 20:22  haoyinuo  阅读(9)  评论(0)    收藏  举报