Mybatis-generator生成Service和Controller
好久记录笔记,这段时间做政府的项目, 数据录入系统基本都是通过 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 = "%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>
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><span> list) {
if(list != null && list.size() > 0<span> ){
FixedAssetsIndicatorExample fixedAssetsIndicatorExample = new<span> FixedAssetsIndicatorExample();
fixedAssetsIndicatorExample.createCriteria().andCountTimeEqualTo(list.get(0<span>).getCountTime());
fixedAssetsIndicatorMapper.deleteByExample(fixedAssetsIndicatorExample);
return<span> fixedAssetsIndicatorMapper.insertBatch(list);
}
return 0<span>;
}
public PageInfo<FixedAssetsIndicator><span> list(ListFixedAssetsIndicatorParam param) {
FixedAssetsIndicatorExample example = new<span> FixedAssetsIndicatorExample();
if(param.getCountTime() != null<span>){
example.createCriteria().andCountTimeEqualTo(param.getCountTime());
}
PageHelper.startPage(param.getPageNum(), param.getPageSize());
example.setOrderByClause("ORDER_MARK"<span>);
List<FixedAssetsIndicator> fromDB =<span> fixedAssetsIndicatorMapper.selectByExample(example);
PageInfo pageInfo = new<span> PageInfo(fromDB);
return<span> pageInfo;
}
public<span> FixedAssetsIndicator get(String id) {
return<span> fixedAssetsIndicatorMapper.selectByPrimaryKey(id);
}
public void<span> save(FixedAssetsIndicator toDB) {
fixedAssetsIndicatorMapper.insertSelective(toDB);
}
public void<span> delete(String id) {
fixedAssetsIndicatorMapper.deleteByPrimaryKey(id);
}
public void<span> update(FixedAssetsIndicator toDB) {
fixedAssetsIndicatorMapper.updateByPrimaryKeySelective(toDB);
}
}
2-3: 生成 controller: 添加 excel 导入导出接口 (基于 easypoi 导入导出)
@Slf4j
@Controller
@RequestMapping("/fixedAssetsIndicator")
@Api(description = "能源投资统计科: 分市固定资产投资主要指标")
public class FixedAssetsIndicatorController extends BaseController {
@Autowired
private<span> FixedAssetsIndicatorService fixedAssetsIndicatorService;
@ApiOperation(value = "列表查询", httpMethod = "POST"<span>)
@RequestMapping("/list.do"<span>)
@ResponseBody
public JSONResult list(@Validated ListFixedAssetsIndicatorParam param) throws<span> ShsoftException {
JSONResult result = new<span> JSONResult(fixedAssetsIndicatorService.list(param));
return<span> result;
}
@ApiOperation(value = "单条查询", httpMethod = "POST"<span>)
@RequestMapping("/get.do"<span>)
@ResponseBody
public JSONResult get(String id) throws<span> ShsoftException {
JSONResult result = new<span> JSONResult(fixedAssetsIndicatorService.get(id));
return<span> result;
}
@ApiOperation(value = "删除", httpMethod = "POST"<span>)
@RequestMapping("/delete.do"<span>)
@ResponseBody
public JSONResult delete(String id) throws<span> ShsoftException {
fixedAssetsIndicatorService.delete(id);
return new<span> JSONResult();
}
@ApiOperation(value = "新增", httpMethod = "POST"<span>)
@RequestMapping("/save.do"<span>)
@ResponseBody
public JSONResult save(@Validated FixedAssetsIndicator toDB) throws<span> ShsoftException {
toDB.setId(new<span> UUIDFactory().generate().toString());
fixedAssetsIndicatorService.save(toDB);
return new<span> JSONResult();
}
@ApiOperation(value = "修改", httpMethod = "POST"<span>)
@RequestMapping("/update.do"<span>)
@ResponseBody
public JSONResult update(@Validated FixedAssetsIndicator toDB) throws<span> ShsoftException {
fixedAssetsIndicatorService.update(toDB);
return new<span> JSONResult();
}
@ApiOperation(value = "导出", httpMethod = "POST"<span>)
@RequestMapping("/export.do"<span>)
@ResponseBody
public JSONResult exportExcel(@Validated ListFixedAssetsIndicatorParam param, HttpServletRequest request, HttpServletResponse response) throws<span> ShsoftException {
JSONResult result = new<span> JSONResult();
PageInfo<FixedAssetsIndicator> pageInfo =<span> fixedAssetsIndicatorService.list(param);
List<FixedAssetsIndicator> list =<span> pageInfo.getList();
List<Map<String, Object>> listMap = new ArrayList<Map<String, Object>><span>();
if(list != null && list.size() > 0<span>){
for (int i = 0; i < list.size(); i++<span>) {
Map<String, Object> lm = new HashMap<String, Object><span>();
if(list.get(i).getCity() != null<span> ){
lm.put("city"<span>, list.get(i).getCity());
}
if(list.get(i).getCityCode() != null<span> ){
lm.put("cityCode"<span>, list.get(i).getCityCode());
}
if(list.get(i).getFixedInvestmentTotal() != null<span> ){
lm.put("fixedInvestmentTotal"<span>, list.get(i).getFixedInvestmentTotal());
}
if(list.get(i).getFixedInvestmentSpeedUp() != null<span> ){
lm.put("fixedInvestmentSpeedUp"<span>, list.get(i).getFixedInvestmentSpeedUp());
}
if(list.get(i).getFolkInvestmentTotal() != null<span> ){
lm.put("folkInvestmentTotal"<span>, list.get(i).getFolkInvestmentTotal());
}
if(list.get(i).getFolkInvestmentSpeedUp() != null<span> ){
lm.put("folkInvestmentSpeedUp"<span>, list.get(i).getFolkInvestmentSpeedUp());
}
listMap.add(lm);
}
}
Calendar calendar =<span> Calendar.getInstance();
calendar.setTime(param.getCountTime());
Map<String, Object> map = new HashMap<String, Object><span>();
map.put("maplist"<span>, listMap);
map.put("year"<span>, calendar.get(Calendar.YEAR));
map.put("month", calendar.get(Calendar.MONTH + 1<span>));
TemplateExportParams params = new TemplateExportParams("excel_temple/固定资产投资/分市固定资产投资主要指标.xls"<span>);
Workbook workbook =<span> ExcelExportUtil.exportExcel(params, map);
OutputStream os = null<span>;
try<span> {
response.setHeader("content-Type", "application/vnd.ms-excel;charset=utf-8"<span>);
response.setHeader("Content-disposition","attachment;filename=分市固定资产投资主要指标.xls"<span>);
os =<span> response.getOutputStream();
workbook.write(os);
os.flush();
} catch<span> (Exception e) {
e.printStackTrace();
}
return<span> result;
}
@ApiOperation(value = "导入", httpMethod = "POST"<span>)
@RequestMapping("/import.do"<span>)
@ResponseBody
public JSONResult importExcel(HttpServletRequest request) throws<span> ShsoftException {
MultipartHttpServletRequest multipartHttpServletRequest =<span> ((MultipartHttpServletRequest) request);
MultipartFile file = multipartHttpServletRequest.getFile("file"<span>);
JSONResult result = new<span> JSONResult();
ImportParams params = new<span> ImportParams();
params.setTitleRows(3<span>);
params.setHeadRows(1<span>);
params.setStartRows(1<span>);
try<span> {
if(file.getSize() > 0<span>){
List<FixedAssetsIndicator> dataList = new ShExcelImportUtils().importExcelByIs(file.getInputStream(), FixedAssetsIndicator.class<span>,
params, false<span>).getList();
fixedAssetsIndicatorService.insertBatch(dataList);
}else<span>{
result = new JSONResult(new<span> ErrorMessage(Error.DAMPE_FIELD_UNAUTH.getCode(),Error.DAMPE_FIELD_UNAUTH.getMessage()));
}
} catch<span> (Exception e) {
throw new<span> ShsoftException(e.getMessage(),e);
}
return<span> result;
}
}
若文章在表述和代码方面如有不妥之处,欢迎批评指正。留下你的脚印,欢迎评论!希望能互相学习。需要源码和 jar 包的留下邮箱