SpringBoot+SqlServer查询接口

SpringBoot+SqlServer查询接口

文章目录

  • SpringBoot+SqlServer查询接口
    • 1. pom环境配置
    • 2. common工具包
    • 3. 实体类+接口+映射
    • 4. Service层+Controller层

需求:根据站号查询前一个小时的所有数据,将数据返回格式为Map>>,即 首先是四个参数,每个参数中有12条数据(每5分钟一条数据,一小时12条),每条数据有参数:日期时间,该参数的值。

要求结果处理如下图:

SpringBoot+SqlServer查询接口_第1张图片

1. pom环境配置

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0modelVersion>

  <groupId>com.zhwygroupId>
  <artifactId>bdly-3dwind-queryartifactId>
  <packaging>jarpackaging>
  <version>1.0-SNAPSHOTversion>

  <name>bdly-3dwind-query Maven Webappname>
  <url>http://maven.apache.orgurl>

  <parent>
    <groupId>org.springframework.bootgroupId>
    <artifactId>spring-boot-starter-parentartifactId>
    <version>1.5.6.RELEASEversion>
  parent>

  <dependencies>

    
    <dependency>
      <groupId>com.microsoft.sqlservergroupId>
      <artifactId>sqljdbc4artifactId>
      <version>4.0version>
    dependency>

    
    <dependency>
      <groupId>org.projectlombokgroupId>
      <artifactId>lombokartifactId>
    dependency>


    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-contextartifactId>
    dependency>

    
    <dependency>
      <groupId>org.mybatis.spring.bootgroupId>
      <artifactId>mybatis-spring-boot-starterartifactId>
      <version>2.3.0version>
    dependency>


    
    <dependency>
      <groupId>org.springframework.bootgroupId>
      <artifactId>spring-boot-starter-webartifactId>
    dependency>

    
    <dependency>
      <groupId>javax.servletgroupId>
      <artifactId>jstlartifactId>
    dependency>

    
    <dependency>
      <groupId>org.apache.tomcat.embedgroupId>
      <artifactId>tomcat-embed-jasperartifactId>
      <scope>providedscope>
    dependency>
    

    <dependency>
      <groupId>org.springframework.bootgroupId>
      <artifactId>spring-boot-starter-data-jpaartifactId>
    dependency>
    <dependency>
      <groupId>org.springframework.bootgroupId>
      <artifactId>spring-boot-starter-webartifactId>
    dependency>

    <dependency>
      <groupId>mysqlgroupId>
      <artifactId>mysql-connector-javaartifactId>
      <scope>runtimescope>
    dependency>
    <dependency>
      <groupId>org.springframework.bootgroupId>
      <artifactId>spring-boot-starter-jdbcartifactId>
    dependency>
    <dependency>
      <groupId>org.springframework.bootgroupId>
      <artifactId>spring-boot-starter-testartifactId>
      <scope>testscope>
    dependency>

    <dependency>
      <groupId>junitgroupId>
      <artifactId>junitartifactId>
      <version>3.8.1version>
      <scope>testscope>
    dependency>
  dependencies>
  <build>
    <finalName>bdly-3dwind-queryfinalName>
    <plugins>
      <plugin>
        <groupId>org.springframework.bootgroupId>
        <artifactId>spring-boot-maven-pluginartifactId>
        <executions>
          <execution>
            <goals>
              <goal>repackagegoal>
            goals>
          execution>
        executions>
      plugin>
    plugins>
  build>
project>

2. common工具包

common工具包

结果返回Result.java

package com.zhwy.common;

import lombok.Data;

/**
 * @author xjz_2002
 * @version 1.0
 */
@Data
public class Result<T> {

    //返回码
    private Integer code;

    //返回消息
    private String message;

    //返回数据
    private T data;


    public Result(){}

    // 返回数据
    protected static <T> Result<T> build(T data) {
        Result<T> result = new Result<T>();
        if (data != null)
            result.setData(data);
        return result;
    }

    public static <T> Result<T> build(T body, Integer code, String message) {
        Result<T> result = build(body);
        result.setCode(code);
        result.setMessage(message);
        return result;
    }

    public static <T> Result<T> build(T body, ResultCodeEnum resultCodeEnum) {
        Result<T> result = build(body);
        result.setCode(resultCodeEnum.getCode());
        result.setMessage(resultCodeEnum.getMessage());
        return result;
    }

    public static<T> Result<T> ok(){
        return Result.ok(null);
    }

    /**
     * 操作成功
     * @param data
     * @param 
     * @return
     */
    public static<T> Result<T> ok(T data){
        Result<T> result = build(data);
        return build(data, ResultCodeEnum.SUCCESS);
    }

    public static<T> Result<T> fail(){
        return Result.fail(null);
    }

    /**
     * 操作失败
     * @param data
     * @param 
     * @return
     */
    public static<T> Result<T> fail(T data){
        Result<T> result = build(data);
        return build(data, ResultCodeEnum.FAIL);
    }

    public Result<T> message(String msg){
        this.setMessage(msg);
        return this;
    }

    public Result<T> code(Integer code){
        this.setCode(code);
        return this;
    }
}

DataType 枚举类

package com.zhwy.common;

import com.zhwy.pojo.SurfChnMulMin;

import java.util.Map;

import static com.zhwy.common.Tool.toStr;

/**
 * @author xjz_2002
 * @version 1.0
 */
public enum DataType {
    PRE("pre"), TEM("tem"), RHU("rhu"), WIN("win");

    private final String code;

    DataType(String code) {
        this.code = code;
    }

    // 基于数据类型填充数据的方法
    public void populateData(Map<String, String> dataMap, SurfChnMulMin scmm) {
        switch (this) {
            case PRE:
                dataMap.put(code, toStr(scmm.getPre()));
                break;
            case TEM:
                dataMap.put(code, toStr(scmm.getTem()));
                break;
            case RHU:
                dataMap.put(code, toStr(scmm.getRhu()));
                break;
            case WIN:
                dataMap.put("win_D", toStr(scmm.getWinDAvg2mi()));
                dataMap.put("win_S", toStr(scmm.getWinSAvg2mi()));
                break;
            // 根据需要添加更多数据类型
        }
    }
}

ResultCodeEnum 枚举返回结果类

package com.zhwy.common;

import lombok.Getter;

/**
 * @author xjz_2002
 * @version 1.0
 */
@Getter
public enum ResultCodeEnum {


    SUCCESS(200,"成功"),
    FAIL(201, "失败"),
    SERVICE_ERROR(2012, "服务异常"),
    DATA_ERROR(204, "数据异常"),
    ILLEGAL_REQUEST(205, "非法请求"),
    REPEAT_SUBMIT(206, "重复提交"),
    ARGUMENT_VALID_ERROR(210, "参数校验异常"),

    LOGIN_AUTH(208, "未登陆"),
    PERMISSION(209, "没有权限"),
    ACCOUNT_ERROR(214, "账号不正确"),
    PASSWORD_ERROR(215, "密码不正确"),
    LOGIN_MOBLE_ERROR( 216, "账号不正确"),
    ACCOUNT_STOP( 217, "账号已停用"),
    NODE_ERROR( 218, "该节点下有子节点,不可以删除")
    ;

    private Integer code;

    private String message;

    private ResultCodeEnum(Integer code, String message) {
        this.code = code;
        this.message = message;
    }

}

Tool 工具类

package com.zhwy.common;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * @author xjz_2002
 * @version 1.0
 */
public class Tool {
	
    public static String toStr(Object obj) {
        String result = "";
        if (obj == null) {
            result = "0";
        } else {
            result = obj.toString();
        }
        return result;
    }

}

3. 实体类+接口+映射

pojo实体类 SurfChnMulMin.java

package com.zhwy.pojo;

import com.fasterxml.jackson.annotation.JsonFormat;

import java.io.Serializable;
import java.util.Date;

public class SurfChnMulMin implements Serializable {
    private String stationIdC;
    private String stationName;
    private Date datetime;
    private Double pre;
    private Double tem;
    private Double rhu;
    private Double winDAvg2mi;
    private Double winSAvg2mi;

    public SurfChnMulMin() {
    }

    public SurfChnMulMin(String stationIdC, String stationName, Date datetime, Double pre, Double tem, Double rhu, Double winDAvg2mi, Double winSAvg2mi) {
        this.stationIdC = stationIdC;
        this.stationName = stationName;
        this.datetime = datetime;
        this.pre = pre;
        this.tem = tem;
        this.rhu = rhu;
        this.winDAvg2mi = winDAvg2mi;
        this.winSAvg2mi = winSAvg2mi;
    }

    public String getStationIdC() {
        return stationIdC;
    }

    public void setStationIdC(String stationIdC) {
        this.stationIdC = stationIdC;
    }

    public String getStationName() {
        return stationName;
    }

    public void setStationName(String stationName) {
        this.stationName = stationName;
    }

    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss",timezone="GMT+8")
    public Date getDatetime() {
        return datetime;
    }

    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss",timezone="GMT+8")
    public void setDatetime(Date datetime) {
        this.datetime = datetime;
    }

    public Double getPre() {
        return pre;
    }

    public void setPre(Double pre) {
        this.pre = pre;
    }

    public Double getTem() {
        return tem;
    }

    public void setTem(Double tem) {
        this.tem = tem;
    }

    public Double getRhu() {
        return rhu;
    }

    public void setRhu(Double rhu) {
        this.rhu = rhu;
    }

    public Double getWinDAvg2mi() {
        return winDAvg2mi;
    }

    public void setWinDAvg2mi(Double winDAvg2mi) {
        this.winDAvg2mi = winDAvg2mi;
    }

    public Double getWinSAvg2mi() {
        return winSAvg2mi;
    }

    public void setWinSAvg2mi(Double winSAvg2mi) {
        this.winSAvg2mi = winSAvg2mi;
    }
}

Mapper接口 ScmmMapper

package com.zhwy.mapper;

import com.zhwy.pojo.SurfChnMulMin;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;

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

/**
 * @author xjz_2002
 * @version 1.0
 */
@Mapper
public interface ScmmMapper{
    //获取最近一小时所有数据
    List<SurfChnMulMin> getScmmList(
            @Param("startTime") String startTime,
            @Param("endTime") String endTime,
            @Param("staId") String staId
    );

    //获取最新时间
    Date getScmmNewDate(
            @Param("staId") String staId
    );

}

Resouces/mapper/ScmmMapper.xml


DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >

<mapper namespace="com.zhwy.mapper.ScmmMapper">
    <select id="getScmmList" resultType="com.zhwy.pojo.SurfChnMulMin">
        SELECT Station_Id_C,
               Station_Name,
               Datetime,
               PRE,
               RHU,
               TEM,
               WIN_D_Avg_2mi,
               WIN_S_Avg_2mi
        FROM SURF_CHN_MUL_MIN
        WHERE (Datetime >= #{startTime} AND Datetime <= #{endTime})
          AND Station_Id_C = #{staId}
    select>

    <select id="getScmmNewDate" resultType="java.util.Date">
        SELECT Datetime
        FROM SURF_CHN_MUL_MIN
        WHERE Station_Id_C = #{staId}
          AND Datetime = (SELECT MAX(Datetime)
                          FROM SURF_CHN_MUL_MIN)
    select>

mapper>

4. Service层+Controller层

service层 ScmmService.java

package com.zhwy.service;

import com.zhwy.common.Result;
import com.zhwy.mapper.ScmmMapper;
import com.zhwy.pojo.SurfChnMulMin;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;

/**
 * @author xjz_2002
 * @version 1.0
 */
@Service
public class ScmmService {

    @Resource
    ScmmMapper scmmMapper;

    // 根据时间段和站号获取天气参数
    public List<SurfChnMulMin> getScmmByDateAndStaId(String times, String staId) {
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime endTimeDate = LocalDateTime.parse(times, dtf);
        LocalDateTime startTimeDate = endTimeDate.minusHours(1);
        String endTime = endTimeDate.format(dtf);
        String startTime = startTimeDate.format(dtf);
        return scmmMapper.getScmmList(startTime,endTime,staId);
    }

    //根据站号获取DB中最新时间
    public String getScmmNewDate(String staId){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date scmmNewDate = scmmMapper.getScmmNewDate(staId);
        return sdf.format(scmmNewDate);
    }


}

Controller层 ScmmController.java

package com.zhwy.controller;

import com.zhwy.common.DataType;
import com.zhwy.common.Result;
import com.zhwy.pojo.SurfChnMulMin;
import com.zhwy.service.ScmmService;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author xjz_2002
 * @version 1.0
 */
@RestController
public class ScmmController {

    @Resource
    ScmmService scmmService;

    // 根据时间段和站号获取天气参数
    @RequestMapping(value = "/getScmmByDateAndStaIdEnum")
    public Result getScmmByDateAndStaId(String staId) {

        //获取数据库中最新日期时间
        String times = scmmService.getScmmNewDate(staId);

        //根据站号查询DB中近一小时所有数据
        List<SurfChnMulMin> scmmList = scmmService.getScmmByDateAndStaId(times, staId);

        //对返回结果进行格式处理
        Map<String, List<Map<String, String>>> resultMap = new HashMap<>();

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        for (DataType dataType : DataType.values()) {

            //dataList存放近一小时数据,根据天气参数返回该参数的值和日期时间
            List<Map<String, String>> dataList = new ArrayList<>();

            //遍历近一小时所有数据,进行处理
            for (SurfChnMulMin scmm : scmmList) {
                Map<String, String> dataMap = new HashMap<>();
                dataMap.put("datetime", sdf.format(scmm.getDatetime()));
                dataType.populateData(dataMap, scmm);
                dataList.add(dataMap);
            }

            resultMap.put(dataType.name().toLowerCase(), dataList);
        }

        return Result.ok(resultMap);
    }
}

application.yml 配置文件

SpringBoot+SqlServer查询接口_第2张图片

效果截图:

SpringBoot+SqlServer查询接口_第3张图片

你可能感兴趣的:(#,Springboot项目实战,spring,boot,sqlserver,后端)