Freemarker generates code

Introduction to FreeMarker

FreeMarker is a template engine . FreeMarker itself is a template. The idea of ​​FreeMarker is to divide the original page into data and templates. When we replace the data and add the templates, we can generate different text files, including HTML, java, etc.

So learning FreeMarker mainly involves learning some of the tags

Simple example

0.Introduce jar package

 <dependency>
    <groupId>org.freemarker</groupId>
    <artifactId>freemarker</artifactId>
    <version>2.3.23</version>
 </dependency>

1. Create a template

package ${clsspath}

public interface ${daoName}Dao{

    public ${daoName} selectOne(${daoName} ${daoName});

    public List<${daoName}> selectAll(${daoName} ${daoName});

    public int insert(${daoName} ${daoName});

    public int update(${daoName} ${daoName});

}

The ${} symbols are placeholders and are used to write data when writing files. The template file suffix is ​​ftl.

2. Writing tools

public void code() {
	Configuration configuration = new Configuration();
	
	// 这里的数据用于插入模板中
	Map<String,Object> map = new HashMap<String, Object>();
	map.put("clsspath", "com.lihao.dao");
	map.put("daoName", "User");
	
	try {
		String path = this.getClass().getClassLoader().getResource("").getPath();
        //设置模板所在文件夹
        configuration.setDirectoryForTemplateLoading(new File(path));
        //模板文件所在位置
		Template t = configuration.getTemplate("Dao.ftl");
		//生成后代码所在位置
		File docFile = new File("UserDao.java");
		Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(docFile)));
		t.process(map, out);
	} catch (Exception e) {
		e.printStackTrace();
	}
}

public static void main(String[] args) {
	FreemarkerUtil f = new FreemarkerUtil();
	f.code();
}

Run the main method. After executing the code, the UserDao.java file will be automatically generated. The generated code is as follows

package com.bdqn.dao

public interface UserDao{

    public User selectOne(User User);

    public List<User> selectAll(User User);

    public int insert(User User);

    public int update(User User);

}

3. The road behind

You can use jdbc to obtain the table structure in the database, and automatically generate some service, dao, and mapper files used in the project based on the data obtained from the table name to reduce your own workload. Interested students can try it by themselves.

Common FreeMarker tags

0. General => ${value name}

1. Comment =》 <#–…–>

2、集合 =》
<#assign seq = [“winter”, “spring”, “summer”, “autumn”]>
<#list seq as x>
${s};
</#list>

3、分支 =》
<#if x == 1>
  x is 1
<#else>
  x is not 1
</#if>

4、分支2 =》
<#if x == 1>
  x is 1
<#elseif x == 2>
  x is 2
<#elseif x == 3>
  x is 3
</#if>

5. Import =》
<#include “/common/copyright.ftl">

Guess you like

Origin blog.csdn.net/lihao1107156171/article/details/103015066