博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
从零搭建自己的SpringBoot后台框架(十)
阅读量:6804 次
发布时间:2019-06-26

本文共 15733 字,大约阅读时间需要 52 分钟。

Hello大家好,本章我们通过freemarker自动生成service,serviceImpl,controller功能 。有问题可以联系我mr_beany@163.com。另求各路大神指点,感谢

一:添加freemarker依赖

org.freemarker
freemarker
2.3.28
复制代码

二:创建service,serviceImpl,controller模板

src\test\java\resources\template\generator下创建

service.ftl

package ${basePackageService};import ${basePackageModel}.${modelNameUpperCamel};import ${basePackage}.core.universal.Service;/*** @Description: ${modelNameUpperCamel}Service接口* @author ${author}* @date ${date}*/public interface ${modelNameUpperCamel}Service extends Service<${modelNameUpperCamel}> {}复制代码

service-impl.ftl

package ${basePackageServiceImpl};import ${basePackageDao}.${modelNameUpperCamel}Mapper;import ${basePackageModel}.${modelNameUpperCamel};import ${basePackageService}.${modelNameUpperCamel}Service;import ${basePackage}.core.universal.AbstractService;import org.springframework.stereotype.Service;import org.springframework.transaction.annotation.Transactional;import javax.annotation.Resource;/*** @Description: ${modelNameUpperCamel}Service接口实现类* @author ${author}* @date ${date}*/@Servicepublic class ${modelNameUpperCamel}ServiceImpl extends AbstractService<${modelNameUpperCamel}> implements ${modelNameUpperCamel}Service {    @Resource    private ${modelNameUpperCamel}Mapper ${modelNameLowerCamel}Mapper;}复制代码

controller.ftl

package ${basePackageController};import ${basePackage}.core.ret.RetResult;import ${basePackage}.core.ret.RetResponse;import ${basePackage}.core.utils.ApplicationUtils;import ${basePackageModel}.${modelNameUpperCamel};import ${basePackageService}.${modelNameUpperCamel}Service;import com.github.pagehelper.PageHelper;import com.github.pagehelper.PageInfo;import org.springframework.web.bind.annotation.PostMapping;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestParam;import org.springframework.web.bind.annotation.RestController;import javax.annotation.Resource;import java.util.List;/*** @Description: ${modelNameUpperCamel}Controller类* @author ${author}* @date ${date}*/@RestController@RequestMapping("/${baseRequestMapping}")public class ${modelNameUpperCamel}Controller {    @Resource    private ${modelNameUpperCamel}Service ${modelNameLowerCamel}Service;    @PostMapping("/insert")    public RetResult
insert(${modelNameUpperCamel} ${modelNameLowerCamel}) throws Exception{ ${modelNameLowerCamel}.setId(ApplicationUtils.getUUID()); Integer state = ${modelNameLowerCamel}Service.insert(${modelNameLowerCamel}); return RetResponse.makeOKRsp(state); } @PostMapping("/deleteById") public RetResult
deleteById(@RequestParam String id) throws Exception { Integer state = ${modelNameLowerCamel}Service.deleteById(id); return RetResponse.makeOKRsp(state); } @PostMapping("/update") public RetResult
update(${modelNameUpperCamel} ${modelNameLowerCamel}) throws Exception { Integer state = ${modelNameLowerCamel}Service.update(${modelNameLowerCamel}); return RetResponse.makeOKRsp(state); } @PostMapping("/selectById") public RetResult<${modelNameUpperCamel}> selectById(@RequestParam String id) throws Exception { ${modelNameUpperCamel} ${modelNameLowerCamel} = ${modelNameLowerCamel}Service.selectById(id); return RetResponse.makeOKRsp(${modelNameLowerCamel}); } /** * @Description: 分页查询 * @param page 页码 * @param size 每页条数 * @Reutrn RetResult
<${modelNameUpperCamel}>> */ @PostMapping("/list") public RetResult
<${modelNameUpperCamel}>> list(@RequestParam(defaultValue = "0") Integer page, @RequestParam(defaultValue = "0") Integer size) throws Exception { PageHelper.startPage(page, size); List<${modelNameUpperCamel}> list = ${modelNameLowerCamel}Service.selectAll(); PageInfo<${modelNameUpperCamel}> pageInfo = new PageInfo<${modelNameUpperCamel}>(list); return RetResponse.makeOKRsp(pageInfo); }}复制代码

三:修改上篇文章中提到的CodeGenerator为如下

package com.example.demo;import com.example.demo.core.constant.ProjectConstant;import com.google.common.base.CaseFormat;import freemarker.template.TemplateExceptionHandler;import org.apache.commons.lang3.StringUtils;import org.mybatis.generator.api.MyBatisGenerator;import org.mybatis.generator.config.*;import org.mybatis.generator.internal.DefaultShellCallback;import java.io.File;import java.io.FileWriter;import java.io.IOException;import java.text.SimpleDateFormat;import java.util.*;/** * @author 张瑶 * @Description: 代码生成器,根据数据表名称生成对应的Model、Mapper、Service、Controller简化开发。 * @date 2018/4/23 20:28 */public class CodeGenerator {    // JDBC配置,请修改为你项目的实际配置    private static final String JDBC_URL = "jdbc:mysql://localhost:3333/demo";    private static final String JDBC_USERNAME = "root";    private static final String JDBC_PASSWORD = "123456";    private static final String JDBC_DIVER_CLASS_NAME = "com.mysql.jdbc.Driver";    // 模板位置    private static final String TEMPLATE_FILE_PATH = "src/test/java/resources/template/generator";    private static final String JAVA_PATH = "src/main/java"; // java文件路径    private static final String RESOURCES_PATH = "src/main/resources";// 资源文件路径    // 生成的Service存放路径    private static final String PACKAGE_PATH_SERVICE = packageConvertPath(ProjectConstant.SERVICE_PACKAGE);    // 生成的Service实现存放路径    private static final String PACKAGE_PATH_SERVICE_IMPL = packageConvertPath(ProjectConstant.SERVICE_IMPL_PACKAGE);    // 生成的Controller存放路径    private static final String PACKAGE_PATH_CONTROLLER = packageConvertPath(ProjectConstant.CONTROLLER_PACKAGE);    // @author    private static final String AUTHOR = "张瑶";    // @date    private static final String DATE = new SimpleDateFormat("yyyy/MM/dd HH:mm").format(new Date());    /**     * genCode("输入表名");     * @param args     */    public static void main(String[] args) {        genCode("system_log");    }    /**     * 通过数据表名称生成代码,Model 名称通过解析数据表名称获得,下划线转大驼峰的形式。 如输入表名称 "t_user_detail" 将生成     * TUserDetail、TUserDetailMapper、TUserDetailService ...     *     * @param tableNames 数据表名称...     */    public static void genCode(String... tableNames) {        for (String tableName : tableNames) {            genCode(tableName);        }    }    /**     * 通过数据表名称生成代码 如输入表名称 "user_info"     * 将生成 UserInfo、UserInfoMapper、UserInfoService ...     *     * @param tableName 数据表名称     */    public static void genCode(String tableName) {        genModelAndMapper(tableName);        genService(tableName);        genController(tableName);    }    public static void genModelAndMapper(String tableName) {        Context context = getContext();        JDBCConnectionConfiguration jdbcConnectionConfiguration = getJDBCConnectionConfiguration();        context.setJdbcConnectionConfiguration(jdbcConnectionConfiguration);        PluginConfiguration pluginConfiguration = getPluginConfiguration();        context.addPluginConfiguration(pluginConfiguration);        JavaModelGeneratorConfiguration javaModelGeneratorConfiguration = getJavaModelGeneratorConfiguration();        context.setJavaModelGeneratorConfiguration(javaModelGeneratorConfiguration);        SqlMapGeneratorConfiguration sqlMapGeneratorConfiguration = getSqlMapGeneratorConfiguration();        context.setSqlMapGeneratorConfiguration(sqlMapGeneratorConfiguration);        JavaClientGeneratorConfiguration javaClientGeneratorConfiguration = getJavaClientGeneratorConfiguration();        context.setJavaClientGeneratorConfiguration(javaClientGeneratorConfiguration);        TableConfiguration tableConfiguration = new TableConfiguration(context);        tableConfiguration.setTableName(tableName);        tableConfiguration.setDomainObjectName(null);        context.addTableConfiguration(tableConfiguration);        List
warnings; MyBatisGenerator generator; try { Configuration config = new Configuration(); config.addContext(context); config.validate(); boolean overwrite = true; DefaultShellCallback callback = new DefaultShellCallback(overwrite); warnings = new ArrayList<>(); generator = new MyBatisGenerator(config, callback, warnings); generator.generate(null); } catch (Exception e) { throw new RuntimeException("生成Model和Mapper失败", e); } if (generator.getGeneratedJavaFiles().isEmpty() || generator.getGeneratedXmlFiles().isEmpty()) { throw new RuntimeException("生成Model和Mapper失败:" + warnings); } String modelName = tableNameConvertUpperCamel(tableName); System.out.println(modelName + ".java 生成成功"); System.out.println(modelName + "Mapper.java 生成成功"); System.out.println(modelName + "Mapper.xml 生成成功"); } public static void genService(String tableName) { try { freemarker.template.Configuration cfg = getConfiguration(); //模板所需要的参数 Map
data = new HashMap<>(); data.put("date", DATE); data.put("author", AUTHOR); String modelNameUpperCamel = tableNameConvertUpperCamel(tableName); data.put("modelNameUpperCamel", modelNameUpperCamel); data.put("modelNameLowerCamel", CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_CAMEL, modelNameUpperCamel)); data.put("basePackage", ProjectConstant.BASE_PACKAGE); data.put("basePackageService", ProjectConstant.SERVICE_PACKAGE); data.put("basePackageServiceImpl", ProjectConstant.SERVICE_IMPL_PACKAGE); data.put("basePackageModel", ProjectConstant.MODEL_PACKAGE); data.put("basePackageDao", ProjectConstant.MAPPER_PACKAGE); File file = new File(JAVA_PATH + PACKAGE_PATH_SERVICE + modelNameUpperCamel + "Service.java"); if (!file.getParentFile().exists()) { file.getParentFile().mkdirs(); } cfg.getTemplate("service.ftl").process(data, new FileWriter(file)); System.out.println(modelNameUpperCamel + "Service.java 生成成功"); File file1 = new File(JAVA_PATH + PACKAGE_PATH_SERVICE_IMPL + modelNameUpperCamel + "ServiceImpl.java"); if (!file1.getParentFile().exists()) { file1.getParentFile().mkdirs(); } cfg.getTemplate("service-impl.ftl").process(data, new FileWriter(file1)); System.out.println(modelNameUpperCamel + "ServiceImpl.java 生成成功"); } catch (Exception e) { throw new RuntimeException("生成Service失败", e); } } public static void genController(String tableName) { try { freemarker.template.Configuration cfg = getConfiguration(); Map
data = new HashMap<>(); data.put("date", DATE); data.put("author", AUTHOR); String modelNameUpperCamel = tableNameConvertUpperCamel(tableName); data.put("baseRequestMapping", CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_CAMEL, modelNameUpperCamel)); data.put("modelNameUpperCamel", modelNameUpperCamel); data.put("modelNameLowerCamel", CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_CAMEL, modelNameUpperCamel)); data.put("basePackage", ProjectConstant.BASE_PACKAGE); data.put("basePackageController", ProjectConstant.CONTROLLER_PACKAGE); data.put("basePackageService", ProjectConstant.SERVICE_PACKAGE); data.put("basePackageModel", ProjectConstant.MODEL_PACKAGE); File file = new File(JAVA_PATH + PACKAGE_PATH_CONTROLLER + modelNameUpperCamel + "Controller.java"); if (!file.getParentFile().exists()) { file.getParentFile().mkdirs(); } cfg.getTemplate("controller.ftl").process(data, new FileWriter(file)); System.out.println(modelNameUpperCamel + "Controller.java 生成成功"); } catch (Exception e) { throw new RuntimeException("生成Controller失败", e); } } private static Context getContext() { Context context = new Context(ModelType.FLAT); context.setId("Potato"); context.setTargetRuntime("MyBatis3Simple"); context.addProperty(PropertyRegistry.CONTEXT_BEGINNING_DELIMITER, "`"); context.addProperty(PropertyRegistry.CONTEXT_ENDING_DELIMITER, "`"); return context; } private static JDBCConnectionConfiguration getJDBCConnectionConfiguration() { JDBCConnectionConfiguration jdbcConnectionConfiguration = new JDBCConnectionConfiguration(); jdbcConnectionConfiguration.setConnectionURL(JDBC_URL); jdbcConnectionConfiguration.setUserId(JDBC_USERNAME); jdbcConnectionConfiguration.setPassword(JDBC_PASSWORD); jdbcConnectionConfiguration.setDriverClass(JDBC_DIVER_CLASS_NAME); return jdbcConnectionConfiguration; } private static PluginConfiguration getPluginConfiguration() { PluginConfiguration pluginConfiguration = new PluginConfiguration(); pluginConfiguration.setConfigurationType("tk.mybatis.mapper.generator.MapperPlugin"); pluginConfiguration.addProperty("mappers", ProjectConstant.MAPPER_INTERFACE_REFERENCE); return pluginConfiguration; } private static JavaModelGeneratorConfiguration getJavaModelGeneratorConfiguration() { JavaModelGeneratorConfiguration javaModelGeneratorConfiguration = new JavaModelGeneratorConfiguration(); javaModelGeneratorConfiguration.setTargetProject(JAVA_PATH); javaModelGeneratorConfiguration.setTargetPackage(ProjectConstant.MODEL_PACKAGE); javaModelGeneratorConfiguration.addProperty("enableSubPackages", "true"); javaModelGeneratorConfiguration.addProperty("trimStrings", "true"); return javaModelGeneratorConfiguration; } private static SqlMapGeneratorConfiguration getSqlMapGeneratorConfiguration() { SqlMapGeneratorConfiguration sqlMapGeneratorConfiguration = new SqlMapGeneratorConfiguration(); sqlMapGeneratorConfiguration.setTargetProject(RESOURCES_PATH); sqlMapGeneratorConfiguration.setTargetPackage("mapper"); return sqlMapGeneratorConfiguration; } private static JavaClientGeneratorConfiguration getJavaClientGeneratorConfiguration() { JavaClientGeneratorConfiguration javaClientGeneratorConfiguration = new JavaClientGeneratorConfiguration(); javaClientGeneratorConfiguration.setTargetProject(JAVA_PATH); javaClientGeneratorConfiguration.setTargetPackage(ProjectConstant.MAPPER_PACKAGE); javaClientGeneratorConfiguration.setConfigurationType("XMLMAPPER"); return javaClientGeneratorConfiguration; } private static freemarker.template.Configuration getConfiguration() throws IOException { freemarker.template.Configuration cfg = new freemarker.template.Configuration(freemarker.template.Configuration.VERSION_2_3_23); cfg.setDirectoryForTemplateLoading(new File(TEMPLATE_FILE_PATH)); cfg.setDefaultEncoding("UTF-8"); cfg.setTemplateExceptionHandler(TemplateExceptionHandler.IGNORE_HANDLER); return cfg; } private static String tableNameConvertUpperCamel(String tableName) { return CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, tableName.toLowerCase()); } private static String packageConvertPath(String packageName) { return String.format("/%s/", packageName.contains(".") ? packageName.replaceAll("\\.", "/") : packageName); }}复制代码

四:功能测试

CodeGenerator中右键run

ok,创建成功

项目地址

码云地址:

GitHub地址:

写文章不易,如对您有帮助,请帮忙点下star

结尾

通过freemarker自动生成service,serviceImpl,controller功能已完成,后续功能接下来陆续更新,有问题可以联系我mr_beany@163.com。另求各路大神指点,感谢大家。

转载地址:http://hznwl.baihongyu.com/

你可能感兴趣的文章
WCF与Web API 区别(应用场景)
查看>>
jQuery常用语法总结笔记
查看>>
JavaScript中的this指向
查看>>
24.访问控制
查看>>
Python - - 面向对象 - - 初始面向对象
查看>>
傻瓜式游戏工具引擎
查看>>
ios安全如何非法窃取用户iTunes Store信息的原理
查看>>
如何定制属于自己的个性化win7主题
查看>>
[转载] ffmpeg 基本数据结构和对象: AVPacket、AVPicture、AVFrame
查看>>
配置阿里yum源
查看>>
Spring MVC基础了解
查看>>
金九银十中,看看这31道Android面试题
查看>>
static 语句块
查看>>
函数节流和函数防抖
查看>>
51CTO专访:谈谈SOC安全管理平台
查看>>
使用USB直接方式解决ESXi识别加密狗的问题
查看>>
创新团队中常见的几种“怪人”
查看>>
FreeBSD从零开始---Web服务器搭建(二)
查看>>
磁盘空间未释放异常案例
查看>>
Windows Server 2008 R2的DHCP高可用
查看>>