转载

基于Springboot的BaseService和BaseController

基于Springboot的BaseService,BaseController

前言:

在做项目时需要对大量的表做增删查改,而其中的逻辑大同小异,所以抽象了一个 BaseService,BaseController来实现所有表的增删查改和一些公用的基础方法。

UML类图:

大体的思路就是在BaseService和BaseController中都使用泛型,到真正创建类的时候才知道具体的对象,对对象进行操作。

代码如下:

BaseEnity(需要使用BaseService方法的实体必须实现这些抽象方法)

package com.honeywell.tms.entity.base;

public abstract class BaseEntity {
    public abstract boolean ValidateEmpty();
    public abstract boolean ValidateUnique();
    public abstract boolean AutoFill();
    public abstract Object getKey();
    public abstract String getText();
}

BaseMapper

逆向后得到的mapper方法都是相同的,所以我把它抽象出来了。

package com.honeywell.tms.dao.base;

import com.honeywell.tms.entity.CompanyEntity;
import com.honeywell.tms.entity.base.BaseEntity;
import org.apache.ibatis.annotations.Param;

import java.util.List;
//所有被BaseService方法调用的dao都需要实现这个接口
public interface BaseMapper<E extends BaseEntity> {
    int deleteByPrimaryKey(@Param(value="ID")Object ID);//在Mapper文件中的占位符的关键字就是value的值

    int insert(E record);

    int insertSelective(E record);

    E selectByPrimaryKey(@Param(value="ID") Object ID);

    List<E> selectAll();

    int updateByPrimaryKeySelective(E record);

    int updateByPrimaryKey(E record);
}

BaseService方法如下

package com.honeywell.tms.service.base;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.honeywell.tms.dao.base.BaseMapper;
import com.honeywell.tms.entity.base.BaseEntity;
import com.honeywell.tms.entity.base.ResponseEntity;
import com.honeywell.tms.entity.base.ValueTextEntity;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

public class BaseService<E extends BaseEntity> {//一些提取了一些公用的Service方法,使用前必须通过init()方法注入相应的Mapper
    BaseMapper dao;

    //在子类构造函数中调用,指明具体的dao层
    public void init(BaseMapper mapper){
        dao=mapper;
    }
    //分页获取
    public ResponseEntity getByPage(int pageNum,int pageSize) {
        PageHelper.startPage(pageNum,pageSize,true);
        ResponseEntity responseEntity=new ResponseEntity();
        List<E>  pageList=dao.selectAll();//这个不是获取到的entity的集合了
        PageInfo<E> entityList=new PageInfo<>(pageList);
        pageList=entityList.getList();
        long count=entityList.getTotal();;
        responseEntity.setData(pageList);
        responseEntity.setTotal(String.valueOf(count));
        return  responseEntity;
    }

    //批量增加
    public ResponseEntity batchSave(List<E> list) {
        ResponseEntity responseEntity=new ResponseEntity();
        StringBuffer message=new StringBuffer();
        int row=0;
        for(E j:list){
            row++;
            if(!j.ValidateEmpty()){
                message.append("第"+row+"行插入失败,请检查是否有违规的空值+/n");
                continue;
            }
            if(!j.ValidateUnique()){
                message.append("第"+row+"行已经存在,插入失败/n");
            }
            j.AutoFill();
            dao.insert(j);
        }
        responseEntity.setMessage(message.toString());
        return responseEntity;
    }

    //批量更新
    public ResponseEntity batchUpdate(List<E> list) {
        ResponseEntity responseEntity=new ResponseEntity();
        StringBuffer message=new StringBuffer();
        int row=0;
        for(E j:list){
            row++;
            if(!j.ValidateEmpty()){
                message.append("第"+row+"行更新失败,请检查是否有违规的空值+/n");
                continue;
            }
            if(!j.ValidateUnique()) {
                message.append("第" + row + "行已经存在,更新失败/n");
            }
            j.AutoFill();
            StringToUUID(j);
            int back=dao.updateByPrimaryKeySelective(j);//不为空的才更新,为空的不更新。
            System.out.println(back);
        }
        responseEntity.setMessage(message.toString());
        return responseEntity;
    }

    //批量删除
    public ResponseEntity batchDestroy(List<E> list) {
        ResponseEntity responseEntity=new ResponseEntity();
        StringBuffer message=new StringBuffer();
        int row=0;
        for(E j:list) {
            row++;
            try{
                StringToUUID(j);
                int count=dao.deleteByPrimaryKey(j.getKey());
            }catch (Exception e){
                System.out.println(e.getMessage());
                message.append("第"+row+"删除失败,请先删除相关引用/n");
            }
        }
        responseEntity.setMessage(message.toString());
        return  responseEntity;
    }
    //获取ValueText模型
    public ResponseEntity getVTModel(){
        ResponseEntity responseEntity=new ResponseEntity();
        List<E> list=dao.selectAll();
        List<ValueTextEntity> vtList=new ArrayList<>();
        for(E j:list){
            ValueTextEntity  vtEntity=new ValueTextEntity();
            vtEntity.setText(j.getText());
            vtEntity.setValue(j.getKey().toString());
            vtList.add(vtEntity);
        }
        responseEntity.setListData(vtList);
        return  responseEntity;

    }
    //将前端页面传来的字符串转为UUID,前提条件是相应属性的名称必须包含"ID"
    public Object StringToUUID(Object obj ){
        Field[] fields=obj.getClass().getDeclaredFields();
        try {
            for (Field field : fields) {
                field.setAccessible(true);
                if (field.getName().contains("ID")) {
                    Object value = field.get(obj);
                    Object uid= UUID.fromString(value.toString());
                    field.set(obj,uid);
                }
            }
        }catch (Exception e){
            System.out.println(e.getMessage());
        }
        return null;
    }




}

BaseController

package com.honeywell.tms.controller.base;

import com.alibaba.fastjson.JSONArray;
import com.honeywell.tms.entity.CompanyEntity;
import com.honeywell.tms.entity.base.BaseEntity;
import com.honeywell.tms.entity.base.ResponseEntity;
import com.honeywell.tms.service.base.BaseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.ParameterizedType;
import java.util.*;

public class BaseController<E extends BaseEntity> {
    private BaseService<E> service;
    private static  final String models="models";

    //初始化
    public void init(BaseService service){
        this.service=service;
    }
    //查询
    public  Map Read(HttpServletRequest request){
        String pageSkip=request.getParameter("pageSkip");
        String pageSize=request.getParameter("pageSize");
        int skip=Integer.valueOf(pageSkip);
        int size=Integer.valueOf(pageSize);
        int pageNum=skip/size+1;
        ResponseEntity responseEntity=service.getByPage(pageNum,size);
        return responseEntity.getMap();
    }

    //增加
    public Map Create(HttpServletRequest request){
        ResponseEntity responseEntity;//返回的实体
        List<E> dataList=getModel(request);
        responseEntity=service.batchSave(dataList);
        responseEntity.setData(dataList);
        return responseEntity.getMap();
    }

    //更新
    public Map Update(HttpServletRequest request){
        ResponseEntity responseEntity;//返回的实体
        List<E> dataList=getModel(request);
        responseEntity=service.batchUpdate(dataList);
        responseEntity.setData(dataList);
        return  responseEntity.getMap();
    }

    //删除
    public Map Destroy(HttpServletRequest request){
        ResponseEntity responseEntity;//返回的实体
        List<E> dataList=getModel(request);
        responseEntity=service.batchDestroy(dataList);
        return responseEntity.getMap();
    }

    //获取ValueText模型
    public List getVTModel(){
        ResponseEntity responseEntity=service.getVTModel();
        return  responseEntity.getListData();
    }

    //从request中获取实体
    public List<E> getModel(HttpServletRequest request){
        String json=request.getParameter(models);
        return JSONArray.parseArray(json,createModel());
    }


    //获取实列的类信息
    public Class createModel()  {
        try {
            ParameterizedType ptype = (ParameterizedType) this.getClass().getGenericSuperclass();
            Class clazz = (Class<E>) ptype.getActualTypeArguments()[0];
            E o = (E) clazz.newInstance();
            return  o.getClass();
        }catch (Exception e){
            System.out.println(e.getMessage());
        }
        return null;

    }
}

使用(用了公司这个实体举例)

公司的实体:

package com.honeywell.tms.entity;


import com.honeywell.tms.dao.CompanyMapper;
import com.honeywell.tms.entity.base.BaseEntity;
import org.springframework.beans.factory.annotation.Autowired;


import java.util.Date;
import java.util.UUID;

public class CompanyEntity  extends BaseEntity {
    @Autowired
    CompanyMapper dao;


    private Object COMPANY_ID;


    private String COMPANY_CODE;


    private String COMPANY_NAME;


    private String COMPANY_ADDR;


    private String CREATED_BY;

    private String UPDATE_BY;

    private Date CREATED_DATE;

    private Date UPDATE_DATE;


    public Object getCOMPANY_ID() {
        return COMPANY_ID;
    }


    public void setCOMPANY_ID(Object COMPANY_ID) {
        this.COMPANY_ID=COMPANY_ID;
    }


    public String getCOMPANY_CODE() {
        return COMPANY_CODE;
    }


    public void setCOMPANY_CODE(String COMPANY_CODE) {
        this.COMPANY_CODE = COMPANY_CODE == null ? null : COMPANY_CODE.trim();
    }


    public String getCOMPANY_NAME() {
        return COMPANY_NAME;
    }


    public void setCOMPANY_NAME(String COMPANY_NAME) {
        this.COMPANY_NAME = COMPANY_NAME == null ? null : COMPANY_NAME.trim();
    }

    public String getCOMPANY_ADDR() {
        return COMPANY_ADDR;
    }


    public void setCOMPANY_ADDR(String COMPANY_ADDR) {
        this.COMPANY_ADDR = COMPANY_ADDR == null ? null : COMPANY_ADDR.trim();
    }


    public String getCREATED_BY() {
        return CREATED_BY;
    }


    public void setCREATED_BY(String CREATED_BY) {
        this.CREATED_BY = CREATED_BY == null ? null : CREATED_BY.trim();
    }


    public String getUPDATE_BY() {
        return UPDATE_BY;
    }


    public void setUPDATE_BY(String UPDATE_BY) {
        this.UPDATE_BY = UPDATE_BY == null ? null : UPDATE_BY.trim();
    }


    public Date getCREATED_DATE() {
        return CREATED_DATE;
    }


    public void setCREATED_DATE(Date CREATED_DATE) {
        this.CREATED_DATE = CREATED_DATE;
    }

    public Date getUPDATE_DATE() {
        return UPDATE_DATE;
    }


    public void setUPDATE_DATE(Date UPDATE_DATE) {
        this.UPDATE_DATE = UPDATE_DATE;
    }

    @Override
    public boolean ValidateEmpty() {
        if(this.COMPANY_CODE==null||this.COMPANY_CODE.equals("")){
            return false;
        }
        if(this.COMPANY_NAME==null||this.COMPANY_NAME.equals("")){
            return false;
        }
        return true;
    }
    @Override
    public boolean ValidateUnique() {
        return true;
    }

    @Override
    public boolean AutoFill(){
        //ID为空说明是新增操作,
        if(getCOMPANY_ID()==null){
            this.setCOMPANY_ID(UUID.randomUUID());
            this.setCREATED_BY("admin");
            this.setCREATED_DATE(new Date());
        }
        this.setUPDATE_BY("admin");
        this.setUPDATE_DATE(new Date());
        return  true;
    }

    @Override
    public Object getKey() {
        return this.COMPANY_ID;
    }
    @Override
    public String getText() {
        return this.COMPANY_NAME;
    }
}

公司的mapper,只需要继承BaseMapper

package com.honeywell.tms.dao;

import com.honeywell.tms.dao.base.BaseMapper;
import com.honeywell.tms.entity.CompanyEntity;
import com.honeywell.tms.entity.base.BaseEntity;

public interface CompanyMapper extends BaseMapper<CompanyEntity> {

}

公司的Service

(继承BaseService,指明相应的实体,构造注入相应的Service)

package com.honeywell.tms.service;
import com.honeywell.tms.dao.CompanyMapper;
import com.honeywell.tms.entity.CompanyEntity;
import com.honeywell.tms.service.base.BaseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


@Service
public class CompanyService extends BaseService<CompanyEntity> {
    private CompanyMapper dao;//如果此处出现红色波浪线 Settings - Editor - Inspections - Spring - Spring Core - Code - Autowiring for Bean Class 勾去掉
    @Autowired
    public CompanyService(CompanyMapper mapper){//这里必须要使用构造注入。
        this.dao=mapper;
        init(dao);
    }



}

公司的Controller

(继承BaseController并构造注入相应的Service就行了,一定要构造注入哟。这里其实映射也可以写在BaseController里面,但是项目用了Swagger,它不支持。)

package com.honeywell.tms.controller;

import com.honeywell.tms.controller.base.BaseController;
import com.honeywell.tms.entity.CompanyEntity;
import com.honeywell.tms.service.CompanyService;
import com.honeywell.tms.service.base.BaseService;
import com.honeywell.tms.utils.consts.Response;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;

@Api(value="/Company",tags = "公司模块")
@RestController
@RequestMapping("/Company")
public class CompanyController extends BaseController<CompanyEntity> {//继承BaseController后可以调用一些基本的方法,不过需要注入相应的Service
    private CompanyService service;
    @Autowired
    public CompanyController(CompanyService service){
        init(service);
    }

    @RequestMapping("/DownloadTemplate")
    @ApiOperation(value = "公司模板下载",notes = "直接下载excel模板")
    @ResponseBody
    public void DownloadTemplate(HttpServletResponse httpServletResponse){
       return;
    }

    @RequestMapping("/Read")
    public Map Read(HttpServletRequest request){
        return  super.Read(request);
    }
    @RequestMapping("Create")
    public Map Create(HttpServletRequest request){
        return  super.Create(request);
    }

    @RequestMapping("/Update")
    public Map Update(HttpServletRequest request){
        return super.Update(request);
    }

    @RequestMapping("/Destroy")
    public Map Destroy(HttpServletRequest request) {
        return super.Destroy(request);
    }

    @RequestMapping("/getVTModel")
    public List getVTModel(HttpServletRequest request){
        return super.getVTModel();
    }


}

总结:总体来说较为满意的,能够实现基本的增删改查和一些基本的方法。缺点是大多都是用继承,没有面向接口编程。UML类图画的不够好,有什么意见或修改的地方请多多指教。

原文  http://www.cnblogs.com/c-lover/p/11380912.html
正文到此结束
Loading...