Toolset Core Tutorial | Part 5: Using Velocity Template Engine to Generate Template Code

Posted by Tonic-_- on Sat, 11 May 2019 04:37:58 +0200

Preface

I don't know if you have such a feeling. In normal development, there are often many duplicate codes in dao and service classes. Velocity provides template generation tools. Today, I will teach you how to say goodbye to these duplicate codes.

Reference items: https://github.com/bigbeef/cppba-codeTemplate
Personal blog: http://www.zhangbox.cn

Be careful

You can write your own template, here for demonstration, you can directly take the cppba-web template to demonstrate, as for the grammar of velocity, you can see this article:
Toolset Core Tutorial | Part 4: Introduction to Velocity Template Engine

maven configuration

 <!-- velocity -->
<dependency>
    <groupId>org.apache.velocity</groupId>
    <artifactId>velocity</artifactId>
    <version>1.7</version>
</dependency>

Create template files

First, look at the directory structure:

For demonstration, I just post ServiceImplTemplate.java. I need other template code to download from my github.

#set ($domain = $!domainName.substring(0,1).toLowerCase()+$!domainName.substring(1))
package $!{packageName}.service.impl;

import $!{packageName}.core.bean.PageEntity;
import $!{packageName}.dao.$!{domainName}Dao;
import $!{packageName}.dto.$!{domainName}Dto;
import $!{packageName}.dto.BaseDto;
import $!{packageName}.entity.$!{domainName};
import $!{packageName}.service.$!{domainName}Service;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * developer
 * nickName:Star
 * email:1342541819@qq.com
 * github:https://github.com/bigbeef
 * velocity Template generation cppba-codeTemplate
 */
@Service
@Transactional
public class $!{domainName}ServiceImpl implements $!{domainName}Service{
    @Resource
    private $!{domainName}Dao $!{domain}Dao;

    @Override
    public void save($!{domainName} $!{domain}) {
        $!{domain}Dao.save($!{domain});
    }

    @Override
    public void delete($!{domainName} $!{domain}) {
        $!{domain}Dao.delete($!{domain});
    }

    @Override
    public void update($!{domainName} $!{domain}) {
        $!{domain}Dao.update($!{domain});
    }

    @Override
    public $!{domainName} findById(int id) {
        return ($!{domainName}) $!{domain}Dao.get($!{domainName}.class, id);
    }

    @Override
    public PageEntity<$!{domainName}> query(BaseDto baseDto) {
        String hql = " select distinct $!{domain} from $!{domainName} $!{domain} where 1=1 ";
        Map params = new HashMap<String,Object>();

        $!{domainName}Dto $!{domain}Dto = ($!{domainName}Dto)baseDto;
        $!{domainName} $!{domain} = $!{domain}Dto.get$!{domainName}();
        int page = $!{domain}Dto.getPage();
        int pageSize = $!{domain}Dto.getPageSize();

        List list = $!{domain}Dao.query(hql,params,page,pageSize);
        long count = $!{domain}Dao.count(hql,params);
        PageEntity<$!{domainName}> pe = new PageEntity<$!{domainName}>();
        pe.setCount(count);
        pe.setList(list);
        return pe;
    }
}

Template generation

Next is the main function to generate the template:

package com.cppba.core;

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.app.VelocityEngine;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * developer
 * nickName:Star
 * email:1342541819@qq.com
 * github:https://github.com/bigbeef
 */

public class Main {

    static String domainName = "Articles"; //Class name
    static String packageName = "com.cppba";//Class package

    static String templateDir = "\\src\\main\\webapp\\template\\";
    static String sourcePath = System.getProperty("user.dir")+templateDir;
    static String resultDir = "\\out";
    static String targetPath = System.getProperty("user.dir")
            + resultDir + "\\"
            + packageName.replace(".", "\\");

    public static void main(String []args) throws Exception{

        Map<String,Object> map = new HashMap();
        map.put("DaoTemplate.java","dao/" + domainName + "Dao.java");
        map.put("ServiceTemplate.java","service/" + domainName + "Service.java");
        map.put("ServiceImplTemplate.java","service/impl/" + domainName + "ServiceImpl.java");
        map.put("DtoTemplate.java","dto/" + domainName + "Dto.java");

        for(String templateFile:map.keySet()){
            String targetFile = (String) map.get(templateFile);
            Properties pro = new Properties();
            pro.setProperty(Velocity.OUTPUT_ENCODING, "UTF-8");
            pro.setProperty(Velocity.INPUT_ENCODING, "UTF-8");
            pro.setProperty(Velocity.FILE_RESOURCE_LOADER_PATH, sourcePath);
            VelocityEngine ve = new VelocityEngine(pro);

            VelocityContext context = new VelocityContext();
            context.put("domainName",domainName);
            context.put("packageName",packageName);

            Template t = ve.getTemplate(templateFile, "UTF-8");

            File file = new File(targetPath, targetFile);
            if (!file.getParentFile().exists())
                file.getParentFile().mkdirs();
            if (!file.exists())
                file.createNewFile();

            FileOutputStream outStream = new FileOutputStream(file);
            OutputStreamWriter writer = new OutputStreamWriter(outStream,
                    "UTF-8");
            BufferedWriter sw = new BufferedWriter(writer);
            t.merge(context, sw);
            sw.flush();
            sw.close();
            outStream.close();
            System.out.println("Successful generation Java file:"
                    + (targetPath + targetFile).replaceAll("/", "\\\\"));
        }
    }
}

Generate java files

We can modify domainName and packageName to modify our package name and class name. Let's run and see:

We see the success of the build. Let's open Articles Service Impl. Java and see:

package com.cppba.service.impl;

import com.cppba.core.bean.PageEntity;
import com.cppba.dao.ArticlesDao;
import com.cppba.dto.ArticlesDto;
import com.cppba.dto.BaseDto;
import com.cppba.entity.Articles;
import com.cppba.service.ArticlesService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * developer
 * nickName:Star
 * email:1342541819@qq.com
 * github:https://github.com/bigbeef
 * velocity Template generation cppba-codeTemplate
 */
@Service
@Transactional
public class ArticlesServiceImpl implements ArticlesService{
    @Resource
    private ArticlesDao articlesDao;

    @Override
    public void save(Articles articles) {
        articlesDao.save(articles);
    }

    @Override
    public void delete(Articles articles) {
        articlesDao.delete(articles);
    }

    @Override
    public void update(Articles articles) {
        articlesDao.update(articles);
    }

    @Override
    public Articles findById(int id) {
        return (Articles) articlesDao.get(Articles.class, id);
    }

    @Override
    public PageEntity<Articles> query(BaseDto baseDto) {
        String hql = " select distinct articles from Articles articles where 1=1 ";
        Map params = new HashMap<String,Object>();

        ArticlesDto articlesDto = (ArticlesDto)baseDto;
        Articles articles = articlesDto.getArticles();
        int page = articlesDto.getPage();
        int pageSize = articlesDto.getPageSize();

        List list = articlesDao.query(hql,params,page,pageSize);
        long count = articlesDao.count(hql,params);
        PageEntity<Articles> pe = new PageEntity<Articles>();
        pe.setCount(count);
        pe.setList(list);
        return pe;
    }
}

Generation success, we copy to the cppba-web can run perfectly!

Written in the end

Welcome to pay attention to, like, and praise the follow-up will launch more toolkit tutorials, please look forward to.
Welcome to my Wechat Public Number for more and more complete learning resources, video materials, technology dry goods!

The Public Number replies "Learning", pulls your process programmer technical discussion group, and shares dry goods resources for the first time.

The public number responds to "Video" and receives 800G Java video learning resources.

The public number replies to the "full stack" and receives the 1T front-end, Java, product manager, Wechat applet, Python and other resources for large release.





The public number replies to "Mu class" and receives 1T Mu class practical learning resources.








The public number replies to "actual combat" and receives 750G project actual combat learning resources.

The public number responds to the "interview" and receives 8G interview practical learning resources.



Topics: MySQL Java github Apache Maven