如何優雅的返回前端想要的數據以及狀態碼

  • DTO-數據傳輸對象;pojo-最純粹的java對象與數據庫中的表一一對應。

       簡單講:DTO起到業務數據的傳遞作用,pojo則與持久層數據庫打交道。

       注:根據命名規範我們命名一般以Exception結尾。

數據庫表結構

-- ----------------------------
-- Table structure for class
-- ----------------------------
DROP TABLE IF EXISTS `class`;
CREATE TABLE `class` (
  `c_id` int(10) NOT NULL,
  `c_name` varchar(255) DEFAULT NULL,
  `teacher_id` int(10) DEFAULT NULL,
  PRIMARY KEY (`c_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of class
-- ----------------------------
INSERT INTO `class` VALUES ('1', '大一', '1');
INSERT INTO `class` VALUES ('2', '大二', '2');
INSERT INTO `class` VALUES ('3', '大三', '3');
INSERT INTO `class` VALUES ('4', '大四', '4');


-- ----------------------------
-- Table structure for teacher
-- ----------------------------
DROP TABLE IF EXISTS `teacher`;
CREATE TABLE `teacher` (
  `t_id` int(10) NOT NULL,
  `t_name` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`t_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of teacher
-- ----------------------------
INSERT INTO `teacher` VALUES ('1', '老和');
INSERT INTO `teacher` VALUES ('2', '老黑');
INSERT INTO `teacher` VALUES ('3', '老黃');
INSERT INTO `teacher` VALUES ('4', '小孩兒');



-- ----------------------------
-- Table structure for student
-- ----------------------------
DROP TABLE IF EXISTS `student`;
CREATE TABLE `student` (
  `s_id` int(10) unsigned NOT NULL,
  `s_name` varchar(255) DEFAULT NULL,
  `age` int(10) DEFAULT NULL,
  `class_id` int(10) DEFAULT NULL,
  `major` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`s_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of student
-- ----------------------------
INSERT INTO `student` VALUES ('1', 'zhangsan', '20', '1', '計算機科學與技術');
INSERT INTO `student` VALUES ('2', 'lisi', '21', '1', '信息安全與技術');
INSERT INTO `student` VALUES ('3', 'wangwu', '22', '2', '離散數學');
INSERT INTO `student` VALUES ('4', 'heer', '23', '2', '微積分理論');
INSERT INTO `student` VALUES ('5', 'huangsan', '24', '3', '英語1');
INSERT INTO `student` VALUES ('6', 'songsi', '25', '3', '英語2');
INSERT INTO `student` VALUES ('7', 'guqi', '26', '4', '日語');

  • yml文件的配置
    
     spring:
       datasource:
         url: jdbc:mysql://localhost:3306/testjpa?useUnicode=true&characterEncoding=UTF-8
         username: root
         password: root
         driver-class-name: com.mysql.jdbc.Driver
    
    #   jpa:
    #     show-sql: true
     #    open-in-view: true
     #  thymeleaf:
      #   cache: false
     #  servlet:
       #  multipart:
       #    max-file-size: 2mb
         #  max-request-size: 50mb
          # location: G:/
    
    #mybatis掃描映射文件
     mybatis:
       mapper-locations: classpath:mapper/*.xml #映射xml文件的位置
    
    
    
      #spring:
      # datasource:
      #   url: jdbc:mysql://localhost:3306/testjpa?useUnicode=true&characterEncoding=UTF-8
      #  username: root
      #   password: root
      #  driver-class-name: com.mysql.jdbc.Driver
      #   show-sql: true  #控制檯打印sql語句
    #pagehelper分頁插件配置
    #mybatis.mapper-locations=classpath:mappings/*.xml
    
    
    #pagehelper分頁插件配置
    #pagehelper.helperDialect=mysql
    #pagehelper.reasonable=true
    #pagehelper.supportMethodsArguments=true
    #pagehelper.params=count=countSql
     server:
       port: 8080
    

     

  • 上代碼:實體類。

      注:這是2個簡單的實體類,包括:Class 班級類;Teacher類。

package com.example.demo.entity.school;

import lombok.Data;

import javax.persistence.Entity;
import javax.persistence.Id;
import java.io.Serializable;
@Data
@Entity
public class Student implements Serializable {
    @Id
    private Integer sId;
    private String sName;
    private Integer age;
    private Integer classId;
    private String major;
}
package com.example.demo.entity.school;

import lombok.Data;

import javax.persistence.*;
import java.io.Serializable;
import java.util.List;

@Entity
@Data
public class Class implements Serializable {
    @Id
    private Integer classId;
    private String className;
    @OneToMany
    private List<Student> students;
    @OneToOne
    private Teacher teacher;


}

注意:@Data爲IDEA的一個lombok插件,自行安裝插件,其功能是省略SET,GET方法,簡化無腦操作。

@OneToOne爲mybatis 一對一操作

@OneToMany爲一多多操作

  • 接口
package com.example.demo.mapper.school;

import com.example.demo.entity.school.Class;
import org.apache.ibatis.annotations.Mapper;

import java.util.List;


@Mapper
public interface ClassMapper {

    Class getClassAndTeacherByClassId(Integer classId);

    List<Class> getClassAndTeacher();

    int getCount();
}
  • 接下里是mapper文件的配置
    <?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.demo.mapper.school.ClassMapper">
        <resultMap id="getClassMap" type="com.example.demo.entity.school.Class">
            <id column="c_id" property="classId"></id>
            <result column="c_name" property="className"></result>
            <association property="teacher" javaType="com.example.demo.entity.school.Teacher">
                <id column="t_id" property="teacherId"></id>
                <result column="t_name" property="teacherName"></result>
            </association>
            <!--
             collection:做一對多關聯查詢的
             ofType:制定幾何中元素對象的類型
            -->
            <collection property="students" ofType="com.example.demo.entity.school.Student">
                <id column="s_id" property="sId"></id>
                <result column="s_name" property="sName"></result>
                <result column="class_id" property="classId"></result>
                <result column="major" property="major"></result>
            </collection>
        </resultMap>
    
        <select id="getClassAndStudent" resultMap="getClassMap">
            SELECT * FROM class a LEFT JOIN student b ON a.c_id = b.class_id
            LEFT JOIN teacher c ON a.teacher_id=c.t_id
        </select>
    
        <select id="getClassAndStudentByClassId" parameterType="int" resultMap="getClassMap">
            SELECT * FROM class a LEFT JOIN student b ON a.c_id = b.class_id
            LEFT JOIN teacher c ON a.teacher_id=c.t_id
            WHERE  a.c_id =#{classId}
        </select>
    
        <select id="getCount" resultType="int">
            SELECT COUNT(*)FROM class a LEFT JOIN student b ON a.c_id = b.class_id
            LEFT JOIN teacher c ON a.teacher_id=c.t_id
    
        </select>
    </mapper>

     

DTO的書寫以及狀態碼的書寫

DTO類:

package com.example.demo.dto;

import lombok.Data;

import java.util.List;

@Data
public class ClassException<T> {
    private int code; // -1:失敗,0成功
    private String message;// 如果返回的是字符串 resType str
    private int count;
    private T data;// 如果調用該方法的時候需要返回一個對象 可以塞進去 resType bean
    private List<T> dataLists;

    //無參構造
    public ClassException() {
    }

    //失敗時調用的構造器
    public ClassException(ClassStateEnum classStateEnum) {
        this.code = classStateEnum.getCode();
        this.message = classStateEnum.getMessage();
    }

    //成功時調用的構造器
    public ClassException(ClassStateEnum classStateEnum, T data) {
        this.code = classStateEnum.getCode();
        this.message = classStateEnum.getMessage();
        this.data = data;
    }
    //成功時調用的構造器


    public ClassException(ClassStateEnum classStateEnum, int count, List<T> dataLists) {
        this.code = classStateEnum.getCode();
        this.message = classStateEnum.getMessage();
        this.count = count;
        this.dataLists = dataLists;
    }
}

狀態碼enum:

package com.example.demo.dto;

/**
 * Create with IntelliJ IDEA.
 *
 * @author: [email protected]
 * Date: 2018/11/8
 * Time: 18:21
 */
public enum ClassStateEnum {
    FAILED(0, "失敗"), SUCCESS(1, "成功");
    private int code;
    private String message;

    ClassStateEnum(int code, String message) {
        this.code = code;
        this.message = message;
    }

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }


    public static ClassStateEnum stateOf(int index) {
        for (ClassStateEnum code : values()) {
            if (code.getCode() == index) {
                return code;
            }
        }
        return null;
    }
}

 

  • SERVICE業務邏輯進行封裝
    package com.example.demo.service.school;
    
    import com.example.demo.common.PageUtil;
    import com.example.demo.common.ResultInfo;
    import com.example.demo.dto.ClassException;
    import com.example.demo.dto.ClassStateEnum;
    import com.example.demo.entity.school.Class;
    import com.example.demo.entity.user.User;
    import com.example.demo.mapper.school.ClassMapper;
    import com.github.pagehelper.PageHelper;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;
    
    import java.util.List;
    
    /**
     * Create with IntelliJ IDEA.
     *
     * @author: [email protected]
     * Date: 2018/10/11
     * Time: 9:48
     */
    @Service
    public class ClassService {
    
        @Autowired
        private ClassMapper classMapper;
    
        public ClassException getClassAndStudentByClassId(Integer classId) {
            if (classId != null) {
                Class classAndStudent = classMapper.getClassAndStudentByClassId(classId);
                return new ClassException(ClassStateEnum.SUCCESS, classAndStudent);
            } else {
                return new ClassException(ClassStateEnum.FAILED);
            }
    
        }
    
        public ClassException getClassAndStudentByClassId(Integer pageNum, Integer pageSize) {
            try {
                if (pageNum == null || pageNum < 1) {
                    pageNum = 1;
                }
                if ((pageSize == null) || (pageSize < 1)) {
                    pageSize = 10;
                }
                PageHelper.startPage(pageNum, pageSize);
                List<Class> classAndStudent = classMapper.getClassAndStudent();
                int count = classMapper.getCount();
                return new ClassException(ClassStateEnum.SUCCESS, count, classAndStudent);
            } catch (Exception e) {
                return new ClassException(ClassStateEnum.FAILED);
            }
        }
    }
    

     

  • CONTROLLER控制層進行前端交互
    package com.example.demo.controller.school;
    
    import com.example.demo.common.ResultInfo;
    import com.example.demo.dto.ClassException;
    import com.example.demo.service.school.ClassService;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestParam;
    import org.springframework.web.bind.annotation.RestController;
    
    /**
     * Create with IntelliJ IDEA.
     *
     * @author: [email protected]
     * Date: 2018/10/11
     * Time: 9:49
     */
    
    @RestController
    public class ClassController {
    
        @Autowired
        private ClassService classService;
    
    
        @RequestMapping(value = "/query_classAndStudent_by_classId")
        public ClassException selectClassAndStudentByClassId(@RequestParam(value = "classId", required = false) Integer classId) {
            return classService.getClassAndStudentByClassId(classId);
        }
    
    
        @RequestMapping(value = "/query_classAndStudent")
        public ClassException selectClassAndStudent(@RequestParam(value = "pageNum", required = false) Integer pageNum,
                                                    @RequestParam(value = "pageSize", required = false) Integer pageSize) {
            return classService.getClassAndStudentByClassId(pageNum, pageSize);
        }
    }
    

    以上就是我的見解:可以看出我這些代碼都是很簡單的,我也實際從事開發不到一年,水平有限,希望大家相互借鑑。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章