springboot+vue+mongodb

使用spring data进行数据操作,前端进行vue进行数据展现。

配置

SpringBoot

maven



    4.0.0
    
        org.springframework.boot
        spring-boot-starter-parent
        2.2.2.RELEASE
         
    
    org.yiva.employee
    employee-admin
    0.0.1-SNAPSHOT
    employee-admin
    Demo project for Spring Boot

    
        1.8
    

    
        
            org.springframework.boot
            spring-boot-starter-actuator
        
        
            org.springframework.boot
            spring-boot-starter-data-mongodb
        
        
            org.springframework.boot
            spring-boot-starter-thymeleaf
        
        
            org.springframework.boot
            spring-boot-starter-web
        
        
            io.springfox
            springfox-swagger2
            2.7.0
        
        
            io.springfox
            springfox-swagger-ui
            2.7.0
        
        
        
            org.projectlombok
            lombok
            1.18.10
            provided
        


        
            org.springframework.boot
            spring-boot-starter-test
            test
            
                
                    org.junit.vintage
                    junit-vintage-engine
                
            
        
    

    
        
            
                org.springframework.boot
                spring-boot-maven-plugin
            
        
    



application.yaml

server:
  port: 9000
  servlet:
    context-path: /v1
spring:
  
  
  
  
  
  
  
  
  data:
    mongodb:
      uri: mongodb://localhost:27017/db_test

swagger

增加swagger注释

@EnableSwagger2
@Configuration
public class SwaggerConfig {

    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                //为当前包路径
                .apis(RequestHandlerSelectors.basePackage("org.yiva.employee.employeeadmin.controller.api"))
                .paths(PathSelectors.any())
                .build();
//        return new Docket(DocumentationType.SWAGGER_2).select().apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class)).build();
    }

    //构建 api文档的详细信息函数,注意这里的注解引用的是哪个
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                //页面标题
                .title("RESTful API")
                //创建人
                .contact(new Contact("Yiva", "http://localhost/", ""))
                //版本号
                .version("1.0")
                //描述
                .description("API 描述")
                .build();
    }
}

SpringBootApp.java

入口文件

@SpringBootApplication
@EnableMongoRepositories(basePackages = "org.yiva.employee.employeeadmin.repositories")
public class EmployeeAdminApplication {

    public static void main(String[] args) {
        SpringApplication.run(EmployeeAdminApplication.class, args);
    }

}

Vue

vue.config.js

module.exports = {
  publicPath: '',
  devServer: {
    host: 'localhost',
    port: 9090,
    proxy: {
      '/api': {
        target: 'http://localhost:9000',
        changeOrigin: true,
        pathRewrite: { '^/api': '/v1' }
      }
    }
  }
}

main.js

import Vue from 'vue'
import App from './App.vue'
import router from './router/index'
import axios from 'axios'
import ViewUI from 'view-design'
import 'view-design/dist/styles/iview.css'

Vue.use(ViewUI)
Vue.config.productionTip = false
Vue.prototype.$http = axios

new Vue({
  el: '#app',
  router,
  render: h => h(App)
}).$mount('#app')

router.js

import Vue from 'vue'
import VueRouter from 'vue-router'
import MainPage from './../views/MainPage.vue'
import CompanyList from './../views/company/CompanyPageList.vue'
import CompanyEdit from './../views/company/CompanyPageEdit.vue'
import PersonList from './../views/person/PersonPageList.vue'
import PersonEdit from './../views/person/PersonPageEdit.vue'
import ContractList from './../views/contract/ContractPageList.vue'
import ContractEdit from './../views/contract/ContractPageEdit.vue'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    name: 'main-view',
    component: MainPage,
    // component: () => import('./../views/v-main.vue')
    children: [
      {
        path: '/company/list',
        name: 'company-list',
        component: CompanyList,
        props: {
          title: '公司列表'
        }
      },
      {
        path: '/company/edit',
        name: 'company-edit',
        component: CompanyEdit,
        props: {
          title: '公司信息录入'
        }
      },
      {
        path: '/person/list',
        name: 'person-list',
        component: PersonList,
        props: {
          title: '人员列表'
        }
      },
      {
        path: '/person/edit',
        name: 'person-edit',
        component: PersonEdit,
        props: {
          title: '人员信息录入'
        }
      },
      {
        path: '/contract/list',
        name: 'contract-list',
        component: ContractList,
        props: {
          title: '合同列表'
        }
      },
      {
        path: '/contract/edit',
        name: 'contract-edit',
        component: ContractEdit,
        props: {
          title: '合同信息录入'
        }
      },
      {
        path: '',
        name: 'company-list',
        component: CompanyList,
        props: {
          title: '公司列表'
        }
      }
    ]
  }
]

const router = new VueRouter({
  routes
})

export default router

实现

SpringBoot

controller

package org.yiva.employee.employeeadmin.controller.api;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.yiva.employee.employeeadmin.pojo.dto.CompanyDTO;
import org.yiva.employee.employeeadmin.pojo.entity.Company;
import org.yiva.employee.employeeadmin.pojo.vo.JsonResult;
import org.yiva.employee.employeeadmin.pojo.vo.ResultStatus;
import org.yiva.employee.employeeadmin.service.CompanyService;

import java.util.List;

@Api(value = "企业信息管理")
@RestController
@RequestMapping(value = "/companies")
public class CompanyApiController {

    @Autowired
    private CompanyService companyService;

    @ApiOperation(value = "单位信息统计")
    @GetMapping("")
    public JsonResult> getCompanies(){
        List companies = companyService.listCompanies();
        return new JsonResult>(companies, ResultStatus.OK);
    }

    @PostMapping(value = "")
    public JsonResult postCompany(@RequestBody Company company) {
        return new JsonResult(companyService.saveCompany(company), ResultStatus.OK);
    }

}

service

package org.yiva.employee.employeeadmin.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.yiva.employee.employeeadmin.pojo.entity.Company;
import org.yiva.employee.employeeadmin.repositories.CompanyRepository;

import java.util.List;

/**
 * 外包单位业务管理类
 */
@Service(value = "companyService")
public class CompanyService {

    @Autowired
    @Qualifier(value = "companyRepository")
    private CompanyRepository companyRepository;

    public List listCompanies() {
        return companyRepository.findAll();
    }

    /**
     * 新增
     * @param company
     * @return
     */
    public boolean saveCompany(Company company) {
        try{
            companyRepository.save(company);
            return true;
        }catch (Exception e){
            return false;
        }


    }
}

dao

package org.yiva.employee.employeeadmin.repositories;

import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Repository;
import org.yiva.employee.employeeadmin.pojo.entity.Company;

@Repository(value = "companyRepository")
public interface CompanyRepository extends MongoRepository {

    Company findCompanyByCompanyName(String name);
}

pojo

  • vo

JsonResult.java

package org.yiva.employee.employeeadmin.pojo.vo;

import lombok.Getter;
import lombok.Setter;
import org.springframework.lang.Nullable;

import java.io.Serializable;

@Getter
@Setter
public class JsonResult implements Serializable {
    private static final long serialVersionUID = 8002676514763088108L;

    private int code;
    private String msg;

    private T data;

    public JsonResult(@Nullable T body, ResultStatus status) {
        this.code = status.getValue();
        this.msg = status.getMsg();
        this.data = body;
    }

    public JsonResult(ResultStatus status) {
        this(null, status);
    }
}

ResultStatus.java

package org.yiva.employee.employeeadmin.pojo.vo;

import lombok.Getter;

@Getter
public enum ResultStatus{

    OK(0,"ok"),
    CONTINUE(100, "Continue"),
    SWITCHING_PROTOCOLS(101, "Switching Protocols"),
    PROCESSING(102, "Processing"),
    CHECKPOINT(103, "Checkpoint"),
    CREATED(201, "Created"),
    ACCEPTED(202, "Accepted"),
    NON_AUTHORITATIVE_INFORMATION(203, "Non-Authoritative Information"),
    NO_CONTENT(204, "No Content"),
    RESET_CONTENT(205, "Reset Content"),
    PARTIAL_CONTENT(206, "Partial Content"),
    MULTI_STATUS(207, "Multi-Status"),
    ALREADY_REPORTED(208, "Already Reported"),
    IM_USED(226, "IM Used"),
    MULTIPLE_CHOICES(300, "Multiple Choices"),
    MOVED_PERMANENTLY(301, "Moved Permanently"),
    FOUND(302, "Found"),
    /** @deprecated */
    @Deprecated
    MOVED_TEMPORARILY(302, "Moved Temporarily"),
    SEE_OTHER(303, "See Other"),
    NOT_MODIFIED(304, "Not Modified"),
    /** @deprecated */
    @Deprecated
    USE_PROXY(305, "Use Proxy"),
    TEMPORARY_REDIRECT(307, "Temporary Redirect"),
    PERMANENT_REDIRECT(308, "Permanent Redirect"),
    BAD_REQUEST(400, "Bad Request"),
    UNAUTHORIZED(401, "Unauthorized"),
    PAYMENT_REQUIRED(402, "Payment Required"),
    FORBIDDEN(403, "Forbidden"),
    NOT_FOUND(404, "Not Found"),
    METHOD_NOT_ALLOWED(405, "Method Not Allowed"),
    NOT_ACCEPTABLE(406, "Not Acceptable"),
    PROXY_AUTHENTICATION_REQUIRED(407, "Proxy Authentication Required"),
    REQUEST_TIMEOUT(408, "Request Timeout"),
    CONFLICT(409, "Conflict"),
    GONE(410, "Gone"),
    LENGTH_REQUIRED(411, "Length Required"),
    PRECONDITION_FAILED(412, "Precondition Failed"),
    PAYLOAD_TOO_LARGE(413, "Payload Too Large"),
    /** @deprecated */
    @Deprecated
    REQUEST_ENTITY_TOO_LARGE(413, "Request Entity Too Large"),
    URI_TOO_LONG(414, "URI Too Long"),
    /** @deprecated */
    @Deprecated
    REQUEST_URI_TOO_LONG(414, "Request-URI Too Long"),
    UNSUPPORTED_MEDIA_TYPE(415, "Unsupported Media Type"),
    REQUESTED_RANGE_NOT_SATISFIABLE(416, "Requested range not satisfiable"),
    EXPECTATION_FAILED(417, "Expectation Failed"),
    I_AM_A_TEAPOT(418, "I'm a teapot"),
    /** @deprecated */
    @Deprecated
    INSUFFICIENT_SPACE_ON_RESOURCE(419, "Insufficient Space On Resource"),
    /** @deprecated */
    @Deprecated
    METHOD_FAILURE(420, "Method Failure"),
    /** @deprecated */
    @Deprecated
    DESTINATION_LOCKED(421, "Destination Locked"),
    UNPROCESSABLE_ENTITY(422, "Unprocessable Entity"),
    LOCKED(423, "Locked"),
    FAILED_DEPENDENCY(424, "Failed Dependency"),
    TOO_EARLY(425, "Too Early"),
    UPGRADE_REQUIRED(426, "Upgrade Required"),
    PRECONDITION_REQUIRED(428, "Precondition Required"),
    TOO_MANY_REQUESTS(429, "Too Many Requests"),
    REQUEST_HEADER_FIELDS_TOO_LARGE(431, "Request Header Fields Too Large"),
    UNAVAILABLE_FOR_LEGAL_REASONS(451, "Unavailable For Legal Reasons"),
    INTERNAL_SERVER_ERROR(500, "Internal Server Error"),
    NOT_IMPLEMENTED(501, "Not Implemented"),
    BAD_GATEWAY(502, "Bad Gateway"),
    SERVICE_UNAVAILABLE(503, "Service Unavailable"),
    GATEWAY_TIMEOUT(504, "Gateway Timeout"),
    HTTP_VERSION_NOT_SUPPORTED(505, "HTTP Version not supported"),
    VARIANT_ALSO_NEGOTIATES(506, "Variant Also Negotiates"),
    INSUFFICIENT_STORAGE(507, "Insufficient Storage"),
    LOOP_DETECTED(508, "Loop Detected"),
    BANDWIDTH_LIMIT_EXCEEDED(509, "Bandwidth Limit Exceeded"),
    NOT_EXTENDED(510, "Not Extended"),
    NETWORK_AUTHENTICATION_REQUIRED(511, "Network Authentication Required");

    private ResultStatus(int value, String msg) {
        this.value = value;
        this.msg = msg;
    }

    private Integer value;
    private String msg;
}

  • entity

Company.java

package org.yiva.employee.employeeadmin.pojo.entity;

import lombok.Getter;
import lombok.Setter;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.index.Indexed;
import org.springframework.data.mongodb.core.mapping.Document;

import javax.validation.constraints.NotNull;
import java.io.Serializable;

@Getter
@Setter
@Document(value = "t_company")
public class Company implements Serializable {

    private static final long serialVersionUID = 5769687450086799084L;
    
    @Id
    private String id;

    @NotNull
    @Indexed(unique = true)
    private String companyName; //公司名
    private String address; //地址

    @Override
    public String toString() {
        return "Company{" +
                "id='" + id + '\'' +
                ", companyName='" + companyName + '\'' +
                ", address='" + address + '\'' +
                '}';
    }
}

Vue

app.vue





MainPage.vue






CompanyPageList.vue



CompanyPageEdit.vue




http请求

vue

this.$http.post(
        'api/companies',
        JSON.stringify(this.company), {
        headers: { 'content-type': 'application/json' }
      }
      ).then(result => {
        let res = result.data.data;
        if (res) {
          this.$Message['success']({
            background: true,
            content: '添加成功'
          });
        } else {
          this.$Message['error']({
            background: true,
            content: '添加失败'
          });
        }
      }).catch(err => {
        this.$Message['warning']({
          background: true,
          content: err
        });
      })

springboot

@Api(value = "企业信息管理")
@RestController
@RequestMapping(value = "/companies")
public class CompanyApiController {

    @Autowired
    private CompanyService companyService;

    @PostMapping(value = "")
    public JsonResult postCompany(@RequestBody Company company) {
        return new JsonResult(companyService.saveCompany(company), ResultStatus.OK);
    }

}

你可能感兴趣的:(springboot+vue+mongodb)