经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » Java相关 » Java » 查看文章
Mybatis-generator生成Service和Controller
来源:cnblogs  作者:Curry_30  时间:2018/12/3 11:33:50  对本文有异议

  好久记录笔记,这段时间做政府的项目,数据录入系统基本都是通过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. <!--生成controller-->
  45. <javaControllerGenerator targetPackage="com.shsoft.platform.ctrl" targetProject="src/main/java">
  46. <property name="superClass" value="com.shsoft.platform.ctrl.BaseController"></property>
  47. </javaControllerGenerator>
  48.  
  49. <!--生成对应表及类名,添加:enableInsertBatch(是否生成批量添加语句,目前只支持oracle),enableInsertBatchIgnore:批量添加语句中忽略的字段-->
  50. <table tableName="SYSTEM_NOTICE" domainObjectName="SystemNotice" enableCountByExample="true" enableUpdateByExample="true"
  51. enableDeleteByExample="true" enableSelectByExample="true" selectByExampleQueryId="false" enableInsertBatch="true"
  52. enableListParam="true">
  53. <property name="enableInsertBatchIgnore" value="createDt"></property>
  54. </table>
  55. </context>
  56. </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. public int insertBatch(List<FixedAssetsIndicator> list) {
  5. if(list != null && list.size() > 0 ){
  6. FixedAssetsIndicatorExample fixedAssetsIndicatorExample = new FixedAssetsIndicatorExample();
  7. fixedAssetsIndicatorExample.createCriteria().andCountTimeEqualTo(list.get(0).getCountTime());
  8. fixedAssetsIndicatorMapper.deleteByExample(fixedAssetsIndicatorExample);
  9. return fixedAssetsIndicatorMapper.insertBatch(list);
  10. }
  11. return 0;
  12. }
  13. public PageInfo<FixedAssetsIndicator> list(ListFixedAssetsIndicatorParam param) {
  14. FixedAssetsIndicatorExample example = new FixedAssetsIndicatorExample();
  15. if(param.getCountTime() != null){
  16. example.createCriteria().andCountTimeEqualTo(param.getCountTime());
  17. }
  18. PageHelper.startPage(param.getPageNum(), param.getPageSize());
  19. example.setOrderByClause("ORDER_MARK");
  20. List<FixedAssetsIndicator> fromDB = fixedAssetsIndicatorMapper.selectByExample(example);
  21. PageInfo pageInfo = new PageInfo(fromDB);
  22. return pageInfo;
  23. }
  24. public FixedAssetsIndicator get(String id) {
  25. return fixedAssetsIndicatorMapper.selectByPrimaryKey(id);
  26. }
  27. public void save(FixedAssetsIndicator toDB) {
  28. fixedAssetsIndicatorMapper.insertSelective(toDB);
  29. }
  30. public void delete(String id) {
  31. fixedAssetsIndicatorMapper.deleteByPrimaryKey(id);
  32. }
  33. public void update(FixedAssetsIndicator toDB) {
  34. fixedAssetsIndicatorMapper.updateByPrimaryKeySelective(toDB);
  35. }
  36. }

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

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

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

 

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号