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

1: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 = &quot;%s&quot;, fixedIndex = %s);@ApiParam(value = &quot;%s&quot;)"/>
<!--设置注解需要的包路径,多个用,分隔-->
<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>

2:执行生成代码

2-1:最后生成 InsertBatch

<insert id="insertBatch" parameterType="java.util.List">
insert into FIXED_ASSETS_INDICATOR (ID, ORDER_MARK, COUNT_TIME,
CITY, CITY_CODE, FIXED_INVESTMENT_TOTAL,
FIXED_INVESTMENT_SPEED_UP, FOLK_INVESTMENT_TOTAL,
FOLK_INVESTMENT_SPEED_UP, REALTY_INVESTMENT_TOTAL,
REALTY_INVESTMENT_SPEED_UP, EMPLOYMENT_INVESTMENT_TOTAL,
EMPLOYMENT_INVESTMENT_SPEED_UP, TECHNOLOGY_INVESTMENT_TOTAL,
TECHNOLOGY_INVESTMENT_SPEED_UP, INFRASTRUCTURE_TOTAL,
INFRASTRUCTURE_SPEED_UP, HIGH_TECH_TOTAL,
HIGH_TECH_SPEED_UP, MANUFACTURING_TOTAL,
MANUFACTURING_SPEED_UP)
<foreach close=")" collection="list" item="item" open="(" separator="UNION">
SELECT #{item.id,jdbcType=VARCHAR}, #{item.orderMark,jdbcType=DECIMAL}, #{item.countTime,jdbcType=TIMESTAMP},
#{item.city,jdbcType=VARCHAR}, #{item.cityCode,jdbcType=VARCHAR}, #{item.fixedInvestmentTotal,jdbcType=DECIMAL},
#{item.fixedInvestmentSpeedUp,jdbcType=FLOAT}, #{item.folkInvestmentTotal,jdbcType=DECIMAL},
#{item.folkInvestmentSpeedUp,jdbcType=FLOAT}, #{item.realtyInvestmentTotal,jdbcType=DECIMAL},
#{item.realtyInvestmentSpeedUp,jdbcType=FLOAT}, #{item.employmentInvestmentTotal,jdbcType=DECIMAL},
#{item.employmentInvestmentSpeedUp,jdbcType=FLOAT}, #{item.technologyInvestmentTotal,jdbcType=DECIMAL},
#{item.technologyInvestmentSpeedUp,jdbcType=FLOAT}, #{item.infrastructureTotal,jdbcType=DECIMAL},
#{item.infrastructureSpeedUp,jdbcType=FLOAT}, #{item.highTechTotal,jdbcType=DECIMAL},
#{item.highTechSpeedUp,jdbcType=FLOAT}, #{item.manufacturingTotal,jdbcType=DECIMAL},
#{item.manufacturingSpeedUp,jdbcType=FLOAT} FROM DUAL
</foreach>
</insert>

2-2:生成service

public class FixedAssetsIndicatorServiceImpl implements FixedAssetsIndicatorService {
@Autowired
private FixedAssetsIndicatorMapper fixedAssetsIndicatorMapper; public int insertBatch(List<FixedAssetsIndicator> list) {
if(list != null && list.size() > 0 ){
FixedAssetsIndicatorExample fixedAssetsIndicatorExample = new FixedAssetsIndicatorExample();
fixedAssetsIndicatorExample.createCriteria().andCountTimeEqualTo(list.get(0).getCountTime());
fixedAssetsIndicatorMapper.deleteByExample(fixedAssetsIndicatorExample);
return fixedAssetsIndicatorMapper.insertBatch(list);
}
return 0;
}
public PageInfo<FixedAssetsIndicator> list(ListFixedAssetsIndicatorParam param) {
FixedAssetsIndicatorExample example = new FixedAssetsIndicatorExample();
if(param.getCountTime() != null){
example.createCriteria().andCountTimeEqualTo(param.getCountTime());
}
PageHelper.startPage(param.getPageNum(), param.getPageSize());
example.setOrderByClause("ORDER_MARK");
List<FixedAssetsIndicator> fromDB = fixedAssetsIndicatorMapper.selectByExample(example);
PageInfo pageInfo = new PageInfo(fromDB);
return pageInfo;
} public FixedAssetsIndicator get(String id) {
return fixedAssetsIndicatorMapper.selectByPrimaryKey(id);
} public void save(FixedAssetsIndicator toDB) {
fixedAssetsIndicatorMapper.insertSelective(toDB);
} public void delete(String id) {
fixedAssetsIndicatorMapper.deleteByPrimaryKey(id);
} public void update(FixedAssetsIndicator toDB) {
fixedAssetsIndicatorMapper.updateByPrimaryKeySelective(toDB);
}
}

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

@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).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());
}
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包的留下邮箱

Mybatis-generator生成Service和Controller的更多相关文章

  1. MyBatis Generator 生成的example 使用 and or 简单混合查询

    MyBatis Generator 生成的example 使用 and or 简单混合查询 参考博客:https://www.cnblogs.com/kangping/p/6001519.html 简 ...

  2. mybatis Generator生成代码及使用方式

    本文原创,转载请注明:http://www.cnblogs.com/fengzheng/p/5889312.html 为什么要有mybatis mybatis 是一个 Java 的 ORM 框架,OR ...

  3. Maven下用MyBatis Generator生成文件

    使用Maven命令用MyBatis Generator生成MyBatis的文件步骤如下: 1.在mop文件内添加plugin <build> <finalName>KenShr ...

  4. MyBatis Generator生成DAO——序列化

    MyBatis Generator生成DAO 的时候,生成的类都是没有序列化的. 还以为要手工加入(開始是手工加入的),今天遇到分页的问题,才发现生成的时候能够加入插件. 既然分页能够有插件.序列化是 ...

  5. 利用org.mybatis.generator生成实体类

    springboot+maven+mybatis+mysql 利用org.mybatis.generator生成实体类 1.添加pom依赖:   2.编写generatorConfig.xml文件 ( ...

  6. 【记录】Mybatis Generator生成数据对象Date/TimeStamp 查询时间格式化

    Mybatis Generator是很好的工具帮助我们生成表映射关联代码,最近博主遇到一个问题,找了很久才解决, 就是用Mybatis Generator生成实体类的时候,Date 时间无法格式化输出 ...

  7. mybatis自动生成service、dao、mapper

    1.config.properties ## 数据库连接参数 jdbc.driverClass = com.mysql.jdbc.Driver jdbc.url = jdbc:mysql://loca ...

  8. mybatis Generator 生成配置文件

    <?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE generatorConfiguration ...

  9. Mybatis Generator生成工具配置文件详解

    <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE generatorConfiguration ...

随机推荐

  1. NodeJs第3方包说明

    formidable 作用:实现简单文件上传 var formidable = require('formidable'); var form = new formidable.IncomingFor ...

  2. Python基础-python数据类型之集合(四)

    集合 集合是一个无序的,不重复的数据组合,基本功能包括关系测试和消除重复元素. 集合对象还支持 union,intersection,difference和 sysmmetric difference ...

  3. 149. Max Points on a Line同一条线上的最多点数

    [抄题]: Given n points on a 2D plane, find the maximum number of points that lie on the same straight ...

  4. C#,如何程序使用正则表达式如何使用匹配的位置的结果修改匹配到的值

    程序代码使用正则表达式如何修改匹配到的值: 代码一: using System; using System.Text.RegularExpressions; public class Example ...

  5. Python列表详解

    #列表:增,删,改,查.names=['N0','N1','N2',['EX1','EX2'],'N3'] '''#------------------------------------------ ...

  6. 【转】权限管理学习 一、ASP.NET Forms身份认证

    [转]权限管理学习 一.ASP.NET Forms身份认证 说明:本文示例使用的VS2017和MVC5. 系统无论大小.牛逼或屌丝,一般都离不开注册.登录.那么接下来我们就来分析下用户身份认证. 简单 ...

  7. SQL笔试基础

    SQLSERVER服务器中,给定表table1 中有两个字段 ID.LastUpdateDate,ID表示更新的事务号,LastUpdateDate表示更新时的服务器时间,请使用一句SQL语句获得最后 ...

  8. 2019.03.01 bzoj3075: [Usaco2013]Necklace(kmp+dp)

    传送门 题意简述:给出S,TS,TS,T两个字串,∣S∣≤10000,∣T∣≤1000|S|\le10000,|T|\le1000∣S∣≤10000,∣T∣≤1000,问至少从SSS中删去几个字符能够 ...

  9. MFC程序执行后台操作时不允许操作界面的一种方法

    在使用MFC编写界面程序时,有时候会遇到像点击按钮后,后台进行大量操作后才显示处理结果这种情况,在后台处理过程中,界面不应该被允许做任何操作,这里介绍一种方法. 解决办法 点击按钮后,弹出一个模态对话 ...

  10. vue全局路由守卫beforeEach

    在main.js里使用方法 router.beforeEach((to,from,next)=>{}) to,是将要跳转的路由, from,是离开的路由 next是个方法,判断to.path 或 ...