mybatisplus2+ 自动生成单表分页查询和Excel导出代码

1.mybatisplus 代码生成类 

TemplateConfig tc = new TemplateConfig();
tc.setController("template/controller.java.vm");这里主要是这个controller模板
import cn.hutool.core.io.FileUtil;
import com.baomidou.mybatisplus.entity.GlobalConfiguration;
import com.baomidou.mybatisplus.enums.IdType;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.rules.DbType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.incrementer.OracleKeyGenerator;

/**
 * @author 万芮睿
 * @create 2018-05-23
 **/
public class MybatisPlusGen {

	public static void main(String[] args) {
		AutoGenerator mpg = new AutoGenerator();
		String tmpDirPath = FileUtil.getParent(FileUtil.getWebRoot().getPath(),1);


		// 全局配置
		GlobalConfig gc = new GlobalConfig();
        gc.setOutputDir(tmpDirPath);
//		gc.setOutputDir("src/main");
		gc.setFileOverride(true);
		gc.setActiveRecord(true);
		gc.setEnableCache(false);// XML 二级缓存
		gc.setBaseResultMap(true);// XML ResultMap
		gc.setBaseColumnList(true);// XML columList
//		gc.setAuthor("xuz");
		gc.setAuthor("万芮睿");
		gc.setIdType(IdType.INPUT);


		// 自定义文件命名,注意 %s 会自动填充表实体属性!
		// gc.setMapperName("%sDao");
		// gc.setXmlName("%sDao");
		// gc.setServiceName("MP%sService");
		// gc.setServiceImplName("%sServiceDiy");
		// gc.setControllerName("%sAction");
		mpg.setGlobalConfig(gc);

		GlobalConfiguration gcf = new GlobalConfiguration();
		//gc.setDbType("oracle");//不需要这么配置了,自动获取数据库类型
		gcf.setKeyGenerator(new OracleKeyGenerator());

		// 数据源配置
		DataSourceConfig dsc = new DataSourceConfig();
		dsc.setDbType(DbType.ORACLE);
//		dsc.setTypeConvert(new MySqlTypeConvert(){
//			// 自定义数据库表字段类型转换【可选】
//			@Override
//			public DbColumnType processTypeConvert(String fieldType) {
//				System.out.println("转换类型:" + fieldType);
//				return super.processTypeConvert(fieldType);
//			}
//		});
//		dsc.setDriverName("oracle.jdbc.driver.OracleDriver");

//		dsc.setUsername("root");
//		dsc.setPassword("123456");
//		dsc.setUrl("jdbc:mysql://192.168.99.100:3306/wms?useUnicode=true&characterEncoding=utf8&useSSL=false");

		mpg.setDataSource(dsc);

		// 策略配置
		StrategyConfig strategy = new StrategyConfig();
		//strategy.setTablePrefix(new String[]{"w_"});// 此处可以修改为您的表前缀
		strategy.setNaming(NamingStrategy.underline_to_camel);// 表名生成策略
		strategy.setEntityLombokModel(true);
//        strategy.setNaming(NamingStrategy.removePrefixAndCamel());// 表名生成策略
		strategy.setInclude("ORDER_MULTIPLE_QUERY_MT");
		// 需要生成的表
//        strategy.setExclude(new String[]{"t_user","t_role","t_permission"}); // 排除生成的表
		// 字段名生成策略
//        strategy.setFieldNaming(NamingStrategy.underline_to_camel);
		// 自定义实体父类
		// strategy.setSuperEntityClass("com.fcs.demo.TestEntity");
		// 自定义实体,公共字段
		// strategy.setSuperEntityColumns(new String[] { "test_id", "age" });
		// 自定义 mapper 父类
		// strategy.setSuperMapperClass("com.fcs.demo.TestMapper");
		// 自定义 service 父类
		// strategy.setSuperServiceClass("com.fcs.demo.TestService");
		// 自定义 service 实现类父类
		// strategy.setSuperServiceImplClass("com.fcs.demo.TestServiceImpl");
		// 自定义 controller 父类
		// strategy.setSuperControllerClass("com.fcs.demo.TestController");
		// 【实体】是否生成字段常量(默认 false)
		// public static final String ID = "test_id";
		// strategy.setEntityColumnConstant(true);
		// 【实体】是否为构建者模型(默认 false)
		// public User1 setName(String name) {this.name = name; return this;}
		// strategy.setEntityBuliderModel(true);
		strategy.setRestControllerStyle(true);
		mpg.setStrategy(strategy);

		// 包配置
		PackageConfig pc = new PackageConfig();
		pc.setParent("com.zhiche.omc");
		pc.setModuleName("omcdomain.model");
        pc.setController("controller");
		pc.setService("service.sys");
		pc.setServiceImpl("impl");
		mpg.setPackageInfo(pc);

		// 注入自定义配置,可以在 VM 中使用 cfg.abc 设置的值
//        InjectionConfig cfg = new InjectionConfig() {
//            @Override
//            public void initMap() {
//                Map<String, Object> map = new HashMap<String, Object>();
//                map.put("abc", this.getConfig().getGlobalConfig().getAuthor() + "-mp");
//                this.setMap(map);
//            }
//        };
//        // 自定义 xxList.jsp 生成
//        List<FileOutConfig> focList = new ArrayList<FileOutConfig>();
//        focList.add(new FileOutConfig("/template/list.jsp.vm") {
//            @Override
//            public String outputFile(TableInfo tableInfo) {
//                // 自定义输入文件名称
//                return "D://my_" + tableInfo.getEntityName() + ".jsp";
//            }
//        });
//        cfg.setFileOutConfigList(focList);
//        mpg.setCfg(cfg);

		// 自定义模板配置,可以 copy 源码 mybatis-plus/src/main/resources/template 下面内容修改,
		// 放置自己项目的 src/main/resources/template 目录下, 默认名称一下可以不配置,也可以自定义模板名称
		 TemplateConfig tc = new TemplateConfig();
//		 tc.setController("...");
		 tc.setEntity("template/entity.java.vm");
		 tc.setController("template/controller.java.vm");
//		 tc.setMapper("...");
//		 tc.setXml("...");
//		 tc.setService("...");
//		 tc.setServiceImpl("...");
		 mpg.setTemplate(tc);

		// 执行生成
		mpg.execute();

		// 打印注入设置
//        System.err.println(mpg.getCfg().getMap().get("abc"));
	}

}

2.controller.java.vm

这有有几点说明 前后端属性名称一直 字符串字段都是用了like 日期字段需要以 S或者E结尾做时间范围

比方说 dateS开始时间  dateE结束时间

package ${package.Controller};


import org.springframework.web.bind.annotation.RequestMapping;

#if(${restControllerStyle})
import org.springframework.web.bind.annotation.RestController;
#else
import org.springframework.stereotype.Controller;
#end
#if(${superControllerClassPackage})
import ${superControllerClassPackage};
#end
import ${package.Entity}.${entity};
import ${superServiceClassPackage};
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.zhiche.omc.omccore.supports.RestfulResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * <p>
 * $!{table.comment} 前端控制器
 * </p>
 *
 * @author ${author}
 * @since ${date}
 */
#if(${restControllerStyle})
@RestController
#else
@Controller
#end
@RequestMapping("/#if(${controllerMappingHyphenStyle})${controllerMappingHyphen}#else${table.entityPath}#end")
#if(${kotlin})
class ${table.controllerName}#if(${superControllerClass}) : ${superControllerClass}()#end

#else
#if(${superControllerClass})
public class ${table.controllerName} extends ${superControllerClass} {
#else
public class ${table.controllerName} {
#end
    private static final Logger LOGGER = LoggerFactory.getLogger(${table.controllerName}.class);

    @Autowired
    ${table.serviceName} thisService;

    @PostMapping(value = "/queryPage")
    public RestfulResponse<Page<${entity}>> queryPage(@RequestBody Page<${entity}> page) {
        RestfulResponse<Page<${entity}>> result = new RestfulResponse<>(0, "success", null);
        EntityWrapper<${entity}> ew = getWrapper(page.getCondition());
        Page<${entity}> thisPage = thisService.selectPage(page.setCondition(null), ew);
        result.setData(thisPage);
        return result;
    }

    private EntityWrapper<${entity}> getWrapper(Map<String, Object> cd) {
            EntityWrapper<${entity}> ew = new EntityWrapper<>();
            #foreach($field in ${table.fields})
                #if(${field.propertyType}=="Date")
                        if (ObjectUtil.isNotEmpty(cd.get("${field.propertyName}S"))) {
                        ew.ge("${field.name}", DateUtil.parse(cd.get("${field.propertyName}S").toString().trim()) );
                        }
                        if (ObjectUtil.isNotEmpty(cd.get("${field.propertyName}E"))) {
                        ew.le("${field.name}", DateUtil.parse(cd.get("${field.propertyName}E").toString().trim()));
                        }
                #else
                        if (ObjectUtil.isNotEmpty(cd.get("${field.propertyName}"))) {
                        ew.like("${field.name}", cd.get("${field.propertyName}").toString().trim());
                        }
                #end
            #end


            return ew;
    }

    @PostMapping(value = "/exportData")
    public void exportData(@RequestBody Page<${entity}> page,HttpServletResponse response) throws IOException {
        EntityWrapper<${entity}> ew = getWrapper(page.getCondition());
        List<${entity}> thisList = thisService.selectList(ew);
        try{
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            String fileName = URLEncoder.encode("${table.comment}", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
            EasyExcel.write(response.getOutputStream(), ${entity}.class).sheet("模板").doWrite(thisList);

        } catch (Exception e) {
            response.reset();
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            Map<String, String> map = new HashMap<String, String>();
            map.put("status", "failure");
            map.put("message", "下载文件失败" + e.getMessage());
            response.getWriter().println(JSON.toJSONString(map));
        }

    }

}
#end

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值