您当前的位置: 首页 >  ar

使用Freemarker生成service和Controller

梁云亮 发布时间:2021-08-16 21:23:10 ,浏览量:8

service接口模板
package com.resume.service;

import com.baomidou.mybatisplus.extension.service.IService;
import com.resume.domain.${className};

import java.util.List;

/**
* @Author: 梁云亮
* @Date: 2021/7/14 13:51
* @Describe:
*/
public interface ${className}Service extends IService {

    /**
    * 查询出所有的可以使用的${comment}信息
    *
    * @return
    */
    List listAllUsable${className}();

    /**
    * 改变指定编号的${comment}的状态
    *
    * @param id
    * @param status
    * @return 返回值表示受影响的记录的行数
    */
    boolean modify${className}Status(Integer id, Integer status);

    /**
    * 根据条件修改${comment}信息
    * @param ${objName}
    * @return
    */
    boolean modify(${className} ${objName});

}
service实现类模板
package com.resume.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.resume.constant.GlobalConst;
import com.resume.domain.${className};
import com.resume.mapper.${className}Mapper;
import com.resume.service.${className}Service;
import org.springframework.stereotype.Service;

import java.util.List;

/**
* @Author: 梁云亮
* @Date: 2021/7/14 13:51
* @Describe:
*/
@Service
public class ${className}ServiceImpl extends ServiceImpl implements ${className}Service {

    @Override
    public List listAllUsable${className}() {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.select("id", "name", "info")
        .eq("status", GlobalConst.Common.STATUS_ENABLE);// 1 表示显示

        List ${objName}List = baseMapper.selectList(queryWrapper);
        return ${objName}List;
    }

    @Override
    public boolean modify${className}Status(Integer id, Integer status) {
        ${className} ${objName} = ${className}.builder()
                                    .id(id)
                                    .status(status)
                                    .build();
        int res = baseMapper.updateById(${objName});
        return res == 1 ? true : false;
    }

    @Override
    public boolean modify(${className} ${objName}) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("id",${objName}.getId());
        int updateRes = baseMapper.update(${objName}, queryWrapper);
        return updateRes == 1 ? true : false;
    }

}
控制器模板
package com.resume.controller;

import com.resume.bean.DataTableResponse;
import com.resume.bean.Result;
import com.resume.bean.ResultUtil;
import com.resume.constant.GlobalConst;
import com.resume.domain.${className};
import com.resume.enums.ResultEnum;
import com.resume.ex.ResumeException;
import com.resume.service.${className}Service;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.List;

/**
* @Author: 梁云亮
* @Date: 2021/7/16 16:17
* @Describe:
*/
@Api(value = "${comment}控制器:${className}Controller",tags = "${className}Controller:${comment}控制器")
@Controller
@RequestMapping("/${objName}")
public class ${className}Controller {

    @Resource
    private ${className}Service ${objName}Service;

    @ApiOperation(value = "打开${comment}列表页面", notes = "打开${comment}列表页面")
    @GetMapping("/open${className}")
    public String open${className}(){
        return "/base/${objName}";
    }

    @ApiOperation(value = "显示${comment}列表", notes = "显示${comment}列表")
    @ResponseBody
    @GetMapping("/v1/list")
    public Result  list() {
        List ${objName}List = ${objName}Service.listAllUsable${className}();

        DataTableResponse dataTableResponse = new DataTableResponse();
        dataTableResponse.setSEcho(3);
        dataTableResponse.setITotalRecords(80L);
        dataTableResponse.setITotalDisplayRecords(70L);
        dataTableResponse.setAaData(${objName}List);
        return ResultUtil.success(200, "数据查询成功", dataTableResponse);
    }

    @ApiOperation(value = "删除${comment}", notes = "根据编号删除${comment}")
    @ResponseBody
    @GetMapping("/v1/remove")
    public Result remove(Integer id) {
        try {
            ${objName}Service.modify${className}Status(id, GlobalConst.Common.STATUS_DISABLE);
            return ResultUtil.success(ResultEnum.SUCCESS);
        } catch (Exception e) {
            throw new ResumeException(ResultEnum.SQL_ERROR);
        }
    }

    @ApiOperation(value = "修改${comment}", notes = "根据编号修改${comment}")
    @ResponseBody
    @GetMapping("/v1/modify")
    public Result modify(${className} ${objName}) {
        try {
            ${objName}Service.modify(${objName});
            return ResultUtil.success(ResultEnum.SUCCESS);
        } catch (Exception e) {
            throw new ResumeException(ResultEnum.SQL_ERROR);
        }
    }

    @ApiOperation(value = "增加${comment}", notes = "增加${comment}")
    @ResponseBody
    @GetMapping("/v1/create")
    public Result create(${className} ${objName}) {
        try {
            ${objName}Service.save(${objName});
            return ResultUtil.success(ResultEnum.SUCCESS);
        } catch (Exception e) {
            throw new ResumeException(ResultEnum.SQL_ERROR);
        }
    }

}
Freemarker工具类
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.Map;

/**
 * @author 梁云亮
 * @description Freemarker工具类
 */
public class FreemarkerUtil {
    /**
     * 根据模板,利用提供的数据,生成文件
     *
     * @param ftlNameWithPath 模板文件
     * @param data            数据
     * @param aimFileName     最终生成的文件
     * @throws IOException
     * @throws TemplateException
     */
    public static void execute(String ftlNameWithPath, Map data, String aimFileName)
            throws IOException, TemplateException {
        Configuration cfg = new Configuration(Configuration.VERSION_2_3_25); // 创建Freemarker配置实例

        int i =
                ftlNameWithPath.lastIndexOf("/") == -1
                        ? ftlNameWithPath.lastIndexOf("\\")
                        : ftlNameWithPath.lastIndexOf("/");

        cfg.setDirectoryForTemplateLoading(new File(ftlNameWithPath.substring(0, i + 1)));

        cfg.setDefaultEncoding("UTF-8");

        Template t1 = cfg.getTemplate(ftlNameWithPath.substring(i + 1)); // 加载模板文件
        Writer out = new FileWriter(new File(aimFileName));
        t1.process(data, out);
        out.flush();
        out.close();
    }
}
测试代码
import freemarker.template.TemplateException;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author: 梁云亮
 * @Date: 2021/7/16 20:40
 * @Describe:
 */
public class GenApplication {
    private static String className = "Project";
    private static String objName = "project";
    private static String comment = "期日经验";

    private static String basePath = "src/main/java/com/resume/";

    public static void main(String[] args) throws IOException, TemplateException {
        // 生成Service接口
        genService(className, objName, comment);

        //生成Service实现类
        genServiceImpl(className, objName);

        // 生成Controller
        genController(className, objName, comment);
    }

    /**
     * 生成Service接口
     *
     * @param className
     * @param objName
     * @throws IOException
     * @throws TemplateException
     */
    private static void genService(String className, String objName, String comment) throws IOException, TemplateException {
        String ftlNameWithPath = basePath + "utils/gen/ftl/service.ftl";
        String aimFileName = basePath + "service/" + className + "Service.java";
        Map map = new HashMap();
        map.put("objName", objName);
        map.put("className", className);
        map.put("comment", comment);
        FreemarkerUtil.execute(ftlNameWithPath, map, aimFileName);
    }

    /**
     * 生成Service实现类
     *
     * @param className
     * @param objName
     * @throws IOException
     * @throws TemplateException
     */
    private static void genServiceImpl(String className, String objName) throws IOException, TemplateException {
        String ftlNameWithPath = basePath + "utils/gen/ftl/serviceImpl.ftl";
        String aimFileName = basePath + "service/impl/" + className + "ServiceImpl.java";
        Map map = new HashMap();
        map.put("objName", objName);
        map.put("className", className);
        FreemarkerUtil.execute(ftlNameWithPath, map, aimFileName);
    }

    /**
     * 生成Controller
     *
     * @param className
     * @param objName
     * @throws IOException
     * @throws TemplateException
     */
    private static void genController(String className, String objName, String comment) throws IOException, TemplateException {
        String ftlNameWithPath = basePath + "utils/gen/ftl/controller.ftl";
        String aimFileName = basePath + "controller/" + className + "Controller.java";
        Map map = new HashMap();
        map.put("objName", objName);
        map.put("className", className);
        map.put("comment", comment);
        FreemarkerUtil.execute(ftlNameWithPath, map, aimFileName);
    }
}
关注
打赏
1688896170
查看更多评论

梁云亮

暂无认证

  • 8浏览

    0关注

    1176博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文
立即登录/注册

微信扫码登录

0.4611s