如何优雅的返回前端想要的数据以及状态码

  • 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);
        }
    }
    

    以上就是我的见解:可以看出我这些代码都是很简单的,我也实际从事开发不到一年,水平有限,希望大家相互借鉴。

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