Mybatis generator生成Service,Controller,新增批量新增資料介面(基於mybatis-generator-1.3.5原始碼修改)
阿新 • • 發佈:2018-11-30
好久記錄筆記,這段時間做政府的專案,資料錄入系統基本都是通過excel匯入,且資料量大,許多也是單表的錄入,這就有很多可以通用的程式碼,如controller,service層的那一套都是可以程式碼生成,添加了一個數據庫批量新增介面(目前只支援oracle),
程式碼是基於mybatis-generator-1.3.5原始碼修改後的,具體的原始碼解析,後面等專案上線後,再好好整理一下,這裡就粗魯的記錄如何使用。
mybatis-generator.xml 配置檔案
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN" "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd"> <generatorConfiguration> <context id="DB2Tables" targetRuntime="MyBatis3"> <!--<plugin type="net.coderbee.mybatis.batch.BatchStatementHandler"></plugin> <plugin type="net.coderbee.mybatis.batch.BatchParameterHandler"></plugin>--> <commentGenerator> <property name="suppressDate" value="true"/> <property name="suppressAllComments" value="true"/> </commentGenerator> <!--資料庫連結地址賬號密碼--> <jdbcConnection driverClass="oracle.jdbc.driver.OracleDriver" connectionURL="jdbc:oracle:thin:@127.0.0.1:1521:test" userId="xxxx" password="xxxx" > <!--開啟讀取資料庫註釋:為了把註釋寫到相對應的註解裡面--> <property name="remarksReporting" value="true"></property> </jdbcConnection> <javaTypeResolver> <property name="forceBigDecimals" value="false"/> </javaTypeResolver> <!--生成Model類存放位置--> <javaModelGenerator targetPackage="com.shsoft.platform.domain" targetProject="src/main/java"> <property name="enableSubPackages" value="true"/> <!--設定註解,%s佔位符,讀取資料庫欄位註釋(多個註解用;分隔),一個佔位符讀取資料庫欄位註釋,第二資料庫欄位排序--> <property name="annotation" value="@Excel(name = "%s", fixedIndex = %s);@ApiParam(value = "%s")"/> <!--設定註解需要的包路徑,多個用,分隔--> <property name="annotationTargetPackage" value="cn.afterturn.easypoi.excel.annotation.Excel,io.swagger.annotations.ApiParam"/> </javaModelGenerator> <!--生成對映檔案存放位置--> <sqlMapGenerator targetPackage="com.shsoft.platform.dao.mapper" targetProject="src/main/java"> <property name="enableSubPackages" value="true"/> </sqlMapGenerator> <!--生成Dao類存放位置--> <javaClientGenerator type="XMLMAPPER" targetPackage="com.shsoft.platform.dao" targetProject="src/main/java"> <property name="enableSubPackages" value="true"/> </javaClientGenerator> <!--生成service,serviceImpl--> <javaServiceGenerator targetPackage="com.shsoft.platform.service" targetProject="src/main/java" implementationPackage="com.shsoft.platform.service"> </javaServiceGenerator> <!--生成controller--> <javaControllerGenerator targetPackage="com.shsoft.platform.ctrl" targetProject="src/main/java"> <property name="superClass" value="com.shsoft.platform.ctrl.BaseController"></property> </javaControllerGenerator> <!--生成對應表及類名,新增:enableInsertBatch(是否生成批量新增語句,目前只支援oracle),enableInsertBatchIgnore:批量新增語句中忽略的欄位--> <table tableName="SYSTEM_NOTICE" domainObjectName="SystemNotice" enableCountByExample="true" enableUpdateByExample="true" enableDeleteByExample="true" enableSelectByExample="true" selectByExampleQueryId="false" enableInsertBatch="true" enableListParam="true"> <property name="enableInsertBatchIgnore" value="createDt"></property> </table> </context> </generatorConfiguration>
執行生成程式碼
最後生成 InsertBatch
生成service
生成controller:新增excel匯入匯出介面(基於easypoi匯入匯出)
package com.shsoft.platform.ctrl; import cn.afterturn.easypoi.excel.ExcelExportUtil; import cn.afterturn.easypoi.excel.entity.ImportParams; import cn.afterturn.easypoi.excel.entity.TemplateExportParams; import com.github.pagehelper.PageInfo; import com.shsoft.common.enums.Error; import com.shsoft.framework.core.exception.ShsoftException; import com.shsoft.framework.core.id.UUIDFactory; import com.shsoft.framework.web.model.ErrorMessage; import com.shsoft.framework.web.model.JSONResult; import com.shsoft.platform.domain.FixedAssetsIndicator; import com.shsoft.platform.domain.ListFixedAssetsIndicatorParam; import com.shsoft.platform.service.ExcelService; import com.shsoft.platform.service.FixedAssetsIndicatorService; import com.shsoft.platform.utils.ShExcelImportParams; import com.shsoft.platform.utils.ShExcelImportUtils; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.time.DateUtils; import org.apache.poi.ss.formula.functions.T; import org.apache.poi.ss.usermodel.Workbook; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.multipart.*; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.util.*; /* * @author lishun * @Description 能源投資統計科:分市固定資產投資主要指標 * @date 2018/9/27 * @param * @return */ @Slf4j @Controller @RequestMapping("/fixedAssetsIndicator") @Api(description = "能源投資統計科:分市固定資產投資主要指標") public class FixedAssetsIndicatorController extends BaseController { @Autowired private FixedAssetsIndicatorService fixedAssetsIndicatorService; @ApiOperation(value = "列表查詢", httpMethod = "POST") @RequestMapping("/list.do") @ResponseBody public JSONResult list(@Validated ListFixedAssetsIndicatorParam param) throws ShsoftException { JSONResult result = new JSONResult(fixedAssetsIndicatorService.list(param)); return result; } @ApiOperation(value = "單條查詢", httpMethod = "POST") @RequestMapping("/get.do") @ResponseBody public JSONResult get(String id) throws ShsoftException { JSONResult result = new JSONResult(fixedAssetsIndicatorService.get(id)); return result; } @ApiOperation(value = "刪除", httpMethod = "POST") @RequestMapping("/delete.do") @ResponseBody public JSONResult delete(String id) throws ShsoftException { fixedAssetsIndicatorService.delete(id); return new JSONResult(); } @ApiOperation(value = "新增", httpMethod = "POST") @RequestMapping("/save.do") @ResponseBody public JSONResult save(@Validated FixedAssetsIndicator toDB) throws ShsoftException { toDB.setId(new UUIDFactory().generate().toString()); fixedAssetsIndicatorService.save(toDB); return new JSONResult(); } @ApiOperation(value = "修改", httpMethod = "POST") @RequestMapping("/update.do") @ResponseBody public JSONResult update(@Validated FixedAssetsIndicator toDB) throws ShsoftException { fixedAssetsIndicatorService.update(toDB); return new JSONResult(); } @ApiOperation(value = "匯出", httpMethod = "POST") @RequestMapping("/export.do") @ResponseBody public JSONResult exportExcel(@Validated ListFixedAssetsIndicatorParam param, HttpServletRequest request, HttpServletResponse response) throws ShsoftException { JSONResult result = new JSONResult(); PageInfo<FixedAssetsIndicator> pageInfo = fixedAssetsIndicatorService.list(param); List<FixedAssetsIndicator> list = pageInfo.getList(); List<Map<String, Object>> listMap = new ArrayList<Map<String, Object>>(); if(list != null && list.size() > 0){ for (int i = 0; i < list.size(); i++) { Map<String, Object> lm = new HashMap<String, Object>(); if(list.get(i).getId() != null ){ lm.put("id", list.get(i).getId()); } if(list.get(i).getCreateDt() != null ){ lm.put("createDt", list.get(i).getCreateDt()); } if(list.get(i).getCountTime() != null ){ lm.put("countTime", list.get(i).getCountTime()); } if(list.get(i).getCity() != null ){ lm.put("city", list.get(i).getCity()); } if(list.get(i).getCityCode() != null ){ lm.put("cityCode", list.get(i).getCityCode()); } if(list.get(i).getFixedInvestmentTotal() != null ){ lm.put("fixedInvestmentTotal", list.get(i).getFixedInvestmentTotal()); } if(list.get(i).getFixedInvestmentSpeedUp() != null ){ lm.put("fixedInvestmentSpeedUp", list.get(i).getFixedInvestmentSpeedUp()); } if(list.get(i).getFolkInvestmentTotal() != null ){ lm.put("folkInvestmentTotal", list.get(i).getFolkInvestmentTotal()); } if(list.get(i).getFolkInvestmentSpeedUp() != null ){ lm.put("folkInvestmentSpeedUp", list.get(i).getFolkInvestmentSpeedUp()); } if(list.get(i).getFixedInvestmentTotal() != null && list.get(i).getFolkInvestmentTotal() != null && list.get(i).getFixedInvestmentTotal() != 0){ Double newVal = Double.valueOf(list.get(i).getFolkInvestmentTotal()) * 100 / Double.valueOf(list.get(i).getFixedInvestmentTotal()); lm.put("fixedInvestmentTotal_folkInvestmentTotal", String.format("%.1f",newVal)); } if(list.get(i).getRealtyInvestmentTotal() != null ){ lm.put("realtyInvestmentTotal", list.get(i).getRealtyInvestmentTotal()); } if(list.get(i).getRealtyInvestmentSpeedUp() != null ){ lm.put("realtyInvestmentSpeedUp", list.get(i).getRealtyInvestmentSpeedUp()); } if(list.get(i).getFixedInvestmentTotal() != null && list.get(i).getRealtyInvestmentTotal() != null && list.get(i).getFixedInvestmentTotal() != 0){ Double newVal = Double.valueOf(list.get(i).getRealtyInvestmentTotal()) * 100 / Double.valueOf(list.get(i).getFixedInvestmentTotal()); lm.put("fixedInvestmentTotal_realtyInvestmentTotal",String.format("%.1f",newVal)); } if(list.get(i).getEmploymentInvestmentTotal() != null ){ lm.put("employmentInvestmentTotal", list.get(i).getEmploymentInvestmentTotal()); } if(list.get(i).getEmploymentInvestmentSpeedUp() != null ){ lm.put("employmentInvestmentSpeedUp", list.get(i).getEmploymentInvestmentSpeedUp()); } if(list.get(i).getFixedInvestmentTotal() != null && list.get(i).getEmploymentInvestmentTotal() != null && list.get(i).getFixedInvestmentTotal() != 0){ Double newVal = Double.valueOf(list.get(i).getEmploymentInvestmentTotal()) * 100 / Double.valueOf(list.get(i).getFixedInvestmentTotal()); lm.put("fixedInvestmentTotal_employmentInvestmentTotal",String.format("%.1f",newVal)); } if(list.get(i).getTechnologyInvestmentTotal() != null ){ lm.put("technologyInvestmentTotal", list.get(i).getTechnologyInvestmentTotal()); } if(list.get(i).getTechnologyInvestmentSpeedUp() != null ){ lm.put("technologyInvestmentSpeedUp", list.get(i).getTechnologyInvestmentSpeedUp()); } if(list.get(i).getFixedInvestmentTotal() != null && list.get(i).getTechnologyInvestmentTotal() != null && list.get(i).getFixedInvestmentTotal() != 0){ Double newVal = Double.valueOf(list.get(i).getTechnologyInvestmentTotal()) * 100 / Double.valueOf(list.get(i).getFixedInvestmentTotal()); lm.put("fixedInvestmentTotal_technologyInvestmentTotal",String.format("%.1f",newVal)); } if(list.get(i).getInfrastructureTotal() != null ){ lm.put("infrastructureTotal", list.get(i).getInfrastructureTotal()); } if(list.get(i).getInfrastructureSpeedUp() != null ){ lm.put("infrastructureSpeedUp", list.get(i).getInfrastructureSpeedUp()); } if(list.get(i).getFixedInvestmentTotal() != null && list.get(i).getInfrastructureTotal() != null && list.get(i).getFixedInvestmentTotal() != 0){ Double newVal = Double.valueOf(list.get(i).getInfrastructureTotal()) * 100 / Double.valueOf(list.get(i).getFixedInvestmentTotal()); lm.put("fixedInvestmentTotal_infrastructureTotal",String.format("%.1f",newVal)); } if(list.get(i).getHighTechTotal() != null ){ lm.put("highTechTotal", list.get(i).getHighTechTotal()); } if(list.get(i).getHighTechSpeedUp() != null ){ lm.put("highTechSpeedUp", list.get(i).getHighTechSpeedUp()); } if(list.get(i).getFixedInvestmentTotal() != null && list.get(i).getHighTechTotal() != null && list.get(i).getFixedInvestmentTotal() != 0){ Double newVal = Double.valueOf(list.get(i).getHighTechTotal()) * 100 / Double.valueOf(list.get(i).getFixedInvestmentTotal()); lm.put("fixedInvestmentTotal_highTechTotal",String.format("%.1f",newVal)); } if(list.get(i).getManufacturingTotal() != null ){ lm.put("manufacturingTotal", list.get(i).getManufacturingTotal()); } if(list.get(i).getManufacturingSpeedUp() != null ){ lm.put("manufacturingSpeedUp", list.get(i).getManufacturingSpeedUp()); } if(list.get(i).getFixedInvestmentTotal() != null && list.get(i).getManufacturingTotal() != null && list.get(i).getFixedInvestmentTotal() != 0){ Double newVal = Double.valueOf(list.get(i).getManufacturingTotal()) * 100 / Double.valueOf(list.get(i).getFixedInvestmentTotal()); lm.put("fixedInvestmentTotal_manufacturingTotal",String.format("%.1f",newVal)); } listMap.add(lm); } } Calendar calendar = Calendar.getInstance(); calendar.setTime(param.getCountTime()); Map<String, Object> map = new HashMap<String, Object>(); map.put("maplist", listMap); map.put("year", calendar.get(Calendar.YEAR)); map.put("month", calendar.get(Calendar.MONTH + 1)); TemplateExportParams params = new TemplateExportParams("excel_temple/固定資產投資/分市固定資產投資主要指標.xls"); Workbook workbook = ExcelExportUtil.exportExcel(params, map); OutputStream os = null; try { response.setHeader("content-Type", "application/vnd.ms-excel;charset=utf-8"); response.setHeader("Content-disposition","attachment;filename=分市固定資產投資主要指標.xls"); os = response.getOutputStream(); workbook.write(os); os.flush(); } catch (Exception e) { e.printStackTrace(); } return result; } @ApiOperation(value = "匯入", httpMethod = "POST") @RequestMapping("/import.do") @ResponseBody public JSONResult importExcel(HttpServletRequest request) throws ShsoftException { MultipartHttpServletRequest multipartHttpServletRequest = ((MultipartHttpServletRequest) request); MultipartFile file = multipartHttpServletRequest.getFile("file"); JSONResult result = new JSONResult(); ImportParams params = new ImportParams(); params.setTitleRows(3); params.setHeadRows(1); params.setStartRows(1); try { if(file.getSize() > 0){ List<FixedAssetsIndicator> dataList = new ShExcelImportUtils().importExcelByIs(file.getInputStream(), FixedAssetsIndicator.class, params, false).getList(); fixedAssetsIndicatorService.insertBatch(dataList); }else{ result = new JSONResult(new ErrorMessage(Error.DAMPE_FIELD_UNAUTH.getCode(),Error.DAMPE_FIELD_UNAUTH.getMessage())); } } catch (Exception e) { throw new ShsoftException(e.getMessage(),e); } return result; } }
若文章在表述和程式碼方面如有不妥之處,歡迎批評指正。留下你的腳印,歡迎評論!希望能互相學習。需要原始碼和jar包的留下郵箱