框架学习

Mybatis-generator生成Service和Controller

 

  好久记录笔记,这段时间做政府的项目,数据录入系统基本都是通过excel导入,且数据量大,许多也是单表的录入,这就有很多可以通用的代码,如controller,service层的那一套都是可以代码生成,添加了一个数据库批量添加接口(目前只支持oracle),代码是基于mybatis-generator-1.3.5源码修改后的,具体的源码解析,后面等项目上线后,再好好整理一下,这里就粗鲁的记录如何使用。

1:mybatis-generator.xml 配置文件


 
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!DOCTYPE generatorConfiguration
  3. PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
  4. "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
  5. <generatorConfiguration>
  6. <context id="DB2Tables" targetRuntime="MyBatis3">
  7. <!--<plugin type="net.coderbee.mybatis.batch.BatchStatementHandler"></plugin>
  8. <plugin type="net.coderbee.mybatis.batch.BatchParameterHandler"></plugin>-->
  9. <commentGenerator>
  10. <property name="suppressDate" value="true"/>
  11. <property name="suppressAllComments" value="true"/>
  12. </commentGenerator>
  13. <!--数据库链接地址账号密码-->
  14. <jdbcConnection driverClass="oracle.jdbc.driver.OracleDriver"
  15. connectionURL="jdbc:oracle:thin:@127.0.0.1:1521:test"
  16. userId="xxxx" password="xxxx" >
  17. <!--开启读取数据库注释:为了把注释写到相对应的注解里面-->
  18. <property name="remarksReporting" value="true"></property>
  19. </jdbcConnection>
  20. <javaTypeResolver>
  21. <property name="forceBigDecimals" value="false"/>
  22. </javaTypeResolver>
  23. <!--生成Model类存放位置-->
  24. <javaModelGenerator targetPackage="com.shsoft.platform.domain" targetProject="src/main/java">
  25. <property name="enableSubPackages" value="true"/>
  26. <!--设置注解,%s占位符,读取数据库字段注释(多个注解用;分隔),一个占位符读取数据库字段注释,第二数据库字段排序-->
  27. <property name="annotation" value="@Excel(name = &quot;%s&quot;, fixedIndex = %s);@ApiParam(value = &quot;%s&quot;)"/>
  28. <!--设置注解需要的包路径,多个用,分隔-->
  29. <property name="annotationTargetPackage" value="cn.afterturn.easypoi.excel.annotation.Excel,io.swagger.annotations.ApiParam"/>
  30. </javaModelGenerator>
  31. <!--生成映射文件存放位置-->
  32. <sqlMapGenerator targetPackage="com.shsoft.platform.dao.mapper" targetProject="src/main/java">
  33. <property name="enableSubPackages" value="true"/>
  34. </sqlMapGenerator>
  35. <!--生成Dao类存放位置-->
  36. <javaClientGenerator type="XMLMAPPER" targetPackage="com.shsoft.platform.dao" targetProject="src/main/java">
  37. <property name="enableSubPackages" value="true"/>
  38. </javaClientGenerator>
  39.  
  40. <!--生成service,serviceImpl-->
  41. <javaServiceGenerator targetPackage="com.shsoft.platform.service" targetProject="src/main/java"
  42. implementationPackage="com.shsoft.platform.service">
  43. </javaServiceGenerator>
  44.  
  45. <!--生成controller-->
  46. <javaControllerGenerator targetPackage="com.shsoft.platform.ctrl" targetProject="src/main/java">
  47. <property name="superClass" value="com.shsoft.platform.ctrl.BaseController"></property>
  48. </javaControllerGenerator>
  49.  
  50. <!--生成对应表及类名,添加:enableInsertBatch(是否生成批量添加语句,目前只支持oracle),enableInsertBatchIgnore:批量添加语句中忽略的字段-->
  51. <table tableName="SYSTEM_NOTICE" domainObjectName="SystemNotice" enableCountByExample="true" enableUpdateByExample="true"
  52. enableDeleteByExample="true" enableSelectByExample="true" selectByExampleQueryId="false" enableInsertBatch="true"
  53. enableListParam="true">
  54. <property name="enableInsertBatchIgnore" value="createDt"></property>
  55. </table>
  56. </context>
  57. </generatorConfiguration>

2:执行生成代码

2-1:最后生成 InsertBatch


 
  1. <insert id="insertBatch" parameterType="java.util.List">
  2. insert into FIXED_ASSETS_INDICATOR (ID, ORDER_MARK, COUNT_TIME,
  3. CITY, CITY_CODE, FIXED_INVESTMENT_TOTAL,
  4. FIXED_INVESTMENT_SPEED_UP, FOLK_INVESTMENT_TOTAL,
  5. FOLK_INVESTMENT_SPEED_UP, REALTY_INVESTMENT_TOTAL,
  6. REALTY_INVESTMENT_SPEED_UP, EMPLOYMENT_INVESTMENT_TOTAL,
  7. EMPLOYMENT_INVESTMENT_SPEED_UP, TECHNOLOGY_INVESTMENT_TOTAL,
  8. TECHNOLOGY_INVESTMENT_SPEED_UP, INFRASTRUCTURE_TOTAL,
  9. INFRASTRUCTURE_SPEED_UP, HIGH_TECH_TOTAL,
  10. HIGH_TECH_SPEED_UP, MANUFACTURING_TOTAL,
  11. MANUFACTURING_SPEED_UP)
  12. <foreach close=")" collection="list" item="item" open="(" separator="UNION">
  13. SELECT #{item.id,jdbcType=VARCHAR}, #{item.orderMark,jdbcType=DECIMAL}, #{item.countTime,jdbcType=TIMESTAMP},
  14. #{item.city,jdbcType=VARCHAR}, #{item.cityCode,jdbcType=VARCHAR}, #{item.fixedInvestmentTotal,jdbcType=DECIMAL},
  15. #{item.fixedInvestmentSpeedUp,jdbcType=FLOAT}, #{item.folkInvestmentTotal,jdbcType=DECIMAL},
  16. #{item.folkInvestmentSpeedUp,jdbcType=FLOAT}, #{item.realtyInvestmentTotal,jdbcType=DECIMAL},
  17. #{item.realtyInvestmentSpeedUp,jdbcType=FLOAT}, #{item.employmentInvestmentTotal,jdbcType=DECIMAL},
  18. #{item.employmentInvestmentSpeedUp,jdbcType=FLOAT}, #{item.technologyInvestmentTotal,jdbcType=DECIMAL},
  19. #{item.technologyInvestmentSpeedUp,jdbcType=FLOAT}, #{item.infrastructureTotal,jdbcType=DECIMAL},
  20. #{item.infrastructureSpeedUp,jdbcType=FLOAT}, #{item.highTechTotal,jdbcType=DECIMAL},
  21. #{item.highTechSpeedUp,jdbcType=FLOAT}, #{item.manufacturingTotal,jdbcType=DECIMAL},
  22. #{item.manufacturingSpeedUp,jdbcType=FLOAT} FROM DUAL
  23. </foreach>
  24. </insert>

2-2:生成service


 
  1. public class FixedAssetsIndicatorServiceImpl implements FixedAssetsIndicatorService {
  2. @Autowired
  3. private FixedAssetsIndicatorMapper fixedAssetsIndicatorMapper;
  4.  
  5. public int insertBatch(List<FixedAssetsIndicator> list) {
  6. if(list != null && list.size() > 0 ){
  7. FixedAssetsIndicatorExample fixedAssetsIndicatorExample = new FixedAssetsIndicatorExample();
  8. fixedAssetsIndicatorExample.createCriteria().andCountTimeEqualTo(list.get(0).getCountTime());
  9. fixedAssetsIndicatorMapper.deleteByExample(fixedAssetsIndicatorExample);
  10. return fixedAssetsIndicatorMapper.insertBatch(list);
  11. }
  12. return 0;
  13. }
  14. public PageInfo<FixedAssetsIndicator> list(ListFixedAssetsIndicatorParam param) {
  15. FixedAssetsIndicatorExample example = new FixedAssetsIndicatorExample();
  16. if(param.getCountTime() != null){
  17. example.createCriteria().andCountTimeEqualTo(param.getCountTime());
  18. }
  19. PageHelper.startPage(param.getPageNum(), param.getPageSize());
  20. example.setOrderByClause("ORDER_MARK");
  21. List<FixedAssetsIndicator> fromDB = fixedAssetsIndicatorMapper.selectByExample(example);
  22. PageInfo pageInfo = new PageInfo(fromDB);
  23. return pageInfo;
  24. }
  25.  
  26. public FixedAssetsIndicator get(String id) {
  27. return fixedAssetsIndicatorMapper.selectByPrimaryKey(id);
  28. }
  29.  
  30. public void save(FixedAssetsIndicator toDB) {
  31. fixedAssetsIndicatorMapper.insertSelective(toDB);
  32. }
  33.  
  34. public void delete(String id) {
  35. fixedAssetsIndicatorMapper.deleteByPrimaryKey(id);
  36. }
  37.  
  38. public void update(FixedAssetsIndicator toDB) {
  39. fixedAssetsIndicatorMapper.updateByPrimaryKeySelective(toDB);
  40. }
  41. }

2-3:生成controller:添加excel导入导出接口(基于easypoi导入导出)


 
  1. @Slf4j
  2. @Controller
  3. @RequestMapping("/fixedAssetsIndicator")
  4. @Api(description = "能源投资统计科:分市固定资产投资主要指标")
  5. public class FixedAssetsIndicatorController extends BaseController {
  6.  
  7. @Autowired
  8. private FixedAssetsIndicatorService fixedAssetsIndicatorService;
  9.  
  10. @ApiOperation(value = "列表查询", httpMethod = "POST")
  11. @RequestMapping("/list.do")
  12. @ResponseBody
  13. public JSONResult list(@Validated ListFixedAssetsIndicatorParam param) throws ShsoftException {
  14. JSONResult result = new JSONResult(fixedAssetsIndicatorService.list(param));
  15. return result;
  16. }
  17.  
  18. @ApiOperation(value = "单条查询", httpMethod = "POST")
  19. @RequestMapping("/get.do")
  20. @ResponseBody
  21. public JSONResult get(String id) throws ShsoftException {
  22. JSONResult result = new JSONResult(fixedAssetsIndicatorService.get(id));
  23. return result;
  24. }
  25.  
  26. @ApiOperation(value = "删除", httpMethod = "POST")
  27. @RequestMapping("/delete.do")
  28. @ResponseBody
  29. public JSONResult delete(String id) throws ShsoftException {
  30. fixedAssetsIndicatorService.delete(id);
  31. return new JSONResult();
  32. }
  33.  
  34. @ApiOperation(value = "新增", httpMethod = "POST")
  35. @RequestMapping("/save.do")
  36. @ResponseBody
  37. public JSONResult save(@Validated FixedAssetsIndicator toDB) throws ShsoftException {
  38. toDB.setId(new UUIDFactory().generate().toString());
  39. fixedAssetsIndicatorService.save(toDB);
  40. return new JSONResult();
  41. }
  42.  
  43. @ApiOperation(value = "修改", httpMethod = "POST")
  44. @RequestMapping("/update.do")
  45. @ResponseBody
  46. public JSONResult update(@Validated FixedAssetsIndicator toDB) throws ShsoftException {
  47. fixedAssetsIndicatorService.update(toDB);
  48. return new JSONResult();
  49. }
  50.  
  51. @ApiOperation(value = "导出", httpMethod = "POST")
  52. @RequestMapping("/export.do")
  53. @ResponseBody
  54. public JSONResult exportExcel(@Validated ListFixedAssetsIndicatorParam param, HttpServletRequest request, HttpServletResponse response) throws ShsoftException {
  55. JSONResult result = new JSONResult();
  56. PageInfo<FixedAssetsIndicator> pageInfo = fixedAssetsIndicatorService.list(param);
  57. List<FixedAssetsIndicator> list = pageInfo.getList();
  58. List<Map<String, Object>> listMap = new ArrayList<Map<String, Object>>();
  59. if(list != null && list.size() > 0){
  60. for (int i = 0; i < list.size(); i++) {
  61. Map<String, Object> lm = new HashMap<String, Object>();
  62. if(list.get(i).getCity() != null ){
  63. lm.put("city", list.get(i).getCity());
  64. }
  65. if(list.get(i).getCityCode() != null ){
  66. lm.put("cityCode", list.get(i).getCityCode());
  67. }
  68. if(list.get(i).getFixedInvestmentTotal() != null ){
  69. lm.put("fixedInvestmentTotal", list.get(i).getFixedInvestmentTotal());
  70. }
  71. if(list.get(i).getFixedInvestmentSpeedUp() != null ){
  72. lm.put("fixedInvestmentSpeedUp", list.get(i).getFixedInvestmentSpeedUp());
  73. }
  74.  
  75. if(list.get(i).getFolkInvestmentTotal() != null ){
  76. lm.put("folkInvestmentTotal", list.get(i).getFolkInvestmentTotal());
  77. }
  78. if(list.get(i).getFolkInvestmentSpeedUp() != null ){
  79. lm.put("folkInvestmentSpeedUp", list.get(i).getFolkInvestmentSpeedUp());
  80. }
  81. listMap.add(lm);
  82. }
  83. }
  84. Calendar calendar = Calendar.getInstance();
  85. calendar.setTime(param.getCountTime());
  86. Map<String, Object> map = new HashMap<String, Object>();
  87. map.put("maplist", listMap);
  88. map.put("year", calendar.get(Calendar.YEAR));
  89. map.put("month", calendar.get(Calendar.MONTH + 1));
  90. TemplateExportParams params = new TemplateExportParams("excel_temple/固定资产投资/分市固定资产投资主要指标.xls");
  91. Workbook workbook = ExcelExportUtil.exportExcel(params, map);
  92. OutputStream os = null;
  93. try {
  94. response.setHeader("content-Type", "application/vnd.ms-excel;charset=utf-8");
  95. response.setHeader("Content-disposition","attachment;filename=分市固定资产投资主要指标.xls");
  96. os = response.getOutputStream();
  97. workbook.write(os);
  98. os.flush();
  99. } catch (Exception e) {
  100. e.printStackTrace();
  101. }
  102. return result;
  103. }
  104.  
  105. @ApiOperation(value = "导入", httpMethod = "POST")
  106. @RequestMapping("/import.do")
  107. @ResponseBody
  108. public JSONResult importExcel(HttpServletRequest request) throws ShsoftException {
  109. MultipartHttpServletRequest multipartHttpServletRequest = ((MultipartHttpServletRequest) request);
  110. MultipartFile file = multipartHttpServletRequest.getFile("file");
  111. JSONResult result = new JSONResult();
  112. ImportParams params = new ImportParams();
  113. params.setTitleRows(3);
  114. params.setHeadRows(1);
  115. params.setStartRows(1);
  116. try {
  117. if(file.getSize() > 0){
  118. List<FixedAssetsIndicator> dataList = new ShExcelImportUtils().importExcelByIs(file.getInputStream(), FixedAssetsIndicator.class,
  119. params, false).getList();
  120. fixedAssetsIndicatorService.insertBatch(dataList);
  121. }else{
  122. result = new JSONResult(new ErrorMessage(Error.DAMPE_FIELD_UNAUTH.getCode(),Error.DAMPE_FIELD_UNAUTH.getMessage()));
  123. }
  124. } catch (Exception e) {
  125. throw new ShsoftException(e.getMessage(),e);
  126. }
  127. return result;
  128. }
  129.  
  130. }

若文章在表述和代码方面如有不妥之处,欢迎批评指正。留下你的脚印,欢迎评论!希望能互相学习。需要源码和jar包的留下邮箱