Mybatis-generator⽣成Service和Controller
  好久记录笔记,这段时间做政府的项⽬,数据录⼊系统基本都是通过excel导⼊,且数据量⼤,许多也是单表的录⼊,这就有很多可以通⽤的代码,如controller,service层的那⼀套都是可以代码⽣成,添加了⼀个数据库批量添加接⼝(⽬前只⽀持oracle),代码是基于mybatis-generator-1.3.5源码修改后的,具体的源码解析,后⾯等项⽬上线后,再好好整理⼀下,这⾥就粗鲁的记录如何使⽤。
l 配置⽂件
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
PUBLIC "-////DTD MyBatis Generator Configuration 1.0//EN"
"/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
<context id="DB2Tables" targetRuntime="MyBatis3">
<!--<plugin type="batis.batch.BatchStatementHandler"></plugin>
<plugin type="batis.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>
float up<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.l.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.l" targetProject="src/main/java">
<property name="superClass" value="com.l.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}, #{derMark,jdbcType=DECIMAL}, #{untTime,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}, #{altyInvestmentTotal,jdbcType=DECIMAL},
#{altyInvestmentSpeedUp,jdbcType=FLOAT}, #{ploymentInvestmentTotal,jdbcType=DECIMAL},
#{ploymentInvestmentSpeedUp,jdbcType=FLOAT}, #{hnologyInvestmentTotal,jdbcType=DECIMAL},
#{hnologyInvestmentSpeedUp,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();
fixedAssetsIndicatorMapper.deleteByExample(fixedAssetsIndicatorExample);
return fixedAssetsIndicatorMapper.insertBatch(list);
}
return 0;
}
public PageInfo<FixedAssetsIndicator> list(ListFixedAssetsIndicatorParam param) {
FixedAssetsIndicatorExample example = new FixedAssetsIndicatorExample();
CountTime() != null){
}
PageHelper.PageNum(), PageSize());
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 (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, HttpServletReque
st request, HttpServletResponse response) throws ShsoftException {        JSONResult result = new JSONResult();
PageInfo<FixedAssetsIndicator> pageInfo = fixedAssetsIndicatorService.list(param);
List<FixedAssetsIndicator> list = List();
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>();
(i).getCity() != null ){
lm.put("city", (i).getCity());
}
(i).getCityCode() != null ){
lm.put("cityCode", (i).getCityCode());
}
(i).getFixedInvestmentTotal() != null ){
lm.put("fixedInvestmentTotal", (i).getFixedInvestmentTotal());
}
(i).getFixedInvestmentSpeedUp() != null ){
lm.put("fixedInvestmentSpeedUp", (i).getFixedInvestmentSpeedUp());
}
(i).getFolkInvestmentTotal() != null ){
lm.put("folkInvestmentTotal", (i).getFolkInvestmentTotal());
}
(i).getFolkInvestmentSpeedUp() != null ){
lm.put("folkInvestmentSpeedUp", (i).getFolkInvestmentSpeedUp());
}
listMap.add(lm);
}
}
Calendar calendar = Instance();
calendar.CountTime());
Map<String, Object> map = new HashMap<String, Object>();
map.put("maplist", listMap);
map.put("year", (Calendar.YEAR));
map.put("month", (Calendar.MONTH + 1));
TemplateExportParams params = new TemplateExportParams("excel_temple/固定资产投资/分市固定资产投资主要指标.xls");
Workbook workbook = portExcel(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 = OutputStream();
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 = File("file");
JSONResult result = new JSONResult();
ImportParams params = new ImportParams();
params.setTitleRows(3);
params.setHeadRows(1);
params.setStartRows(1);
try {
Size() > 0){
List<FixedAssetsIndicator> dataList = new ShExcelImportUtils().InputStream(), FixedAssetsIndicator.class,
params, false).getList();
fixedAssetsIndicatorService.insertBatch(dataList);
}else{
result = new JSONResult(new ErrorMessage(Error.DAMPE_Code(),Error.DAMPE_Message()));
}
} catch (Exception e) {
throw new Message(),e);
}
return result;
}
}
若⽂章在表述和代码⽅⾯如有不妥之处,欢迎批评指正。留下你的脚印,欢迎评论!希望能互相学习。需要源码和jar包的留下邮箱

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。