Concluded code generator, efficiency gains from a thousandfold

Summary: write a code generator, to devote some thought, I am here to explain the main principles of a direct duplication of work done, of course, a master-door, long way to go Come, happiness and earth.

          Last talked about acquiring database metadata, this is a manual process it take you to achieve. Production Template - "cast -" Render - "io generate the file. Man of few words, said code is as follows:

 

   1. Make a template ftl

           

import java.io.Serializable;
import java.util.Date;
import lombok.Data;

/**
* ${comments}
*
* @author ${author}
* @email ${email}
* @date ${datetime}
*/
@Data
@TableName("${tableName}")
public class ${className}Entity implements Serializable {
private static final long serialVersionUID = 1L;

<#list columns as column>
/**
* ${column.columnComment}
*/
<#if column.columnKey=="PRI">
@TableId
</#if>
private ${map[column.dataType]} ${column.columnName};
</#list>

  2. Type Conversion mainly java database type to type

      

	// 数据库类型 -》java 类型
	private static HashMap map = new HashMap();
	static {
		map.put("varchar","String");
		map.put("int","Integer");
	}

  3. Rendering, io 4 generates all set,

   

    @Resource(name = "mySQLGeneratorDao")
	private GeneratorDao generatorDao;
	@Autowired
	Configuration configuration;
	// 数据库类型 -》java 类型
	private static HashMap map = new HashMap();
	static {
		map.put("varchar","String");
		map.put("int","Integer");
	}

	@Test
	public void contextLoads() throws IOException, TemplateException {

		Template template = configuration.getTemplate("Entity.java.ftl");
		Model model = new BindingAwareConcurrentModel();
		model.addAttribute("table","user");
		model.addAttribute("comments","user");
		model.addAttribute("author","lyc");
		model.addAttribute("email","[email protected]");
		model.addAttribute("datetime","2019-06-22");
		model.addAttribute("tableName","user");
		model.addAttribute("className","User");
		model.addAttribute("map",map);
		
		model.addAttribute("columns",generatorDao.queryColumns("user"));
		String result = FreeMarkerTemplateUtils.processTemplateIntoString(template,model);

		FileOutputStream outputStream = new FileOutputStream("./"+"UserEntity.java");
		IOUtils.write(result,outputStream,"utf-8");
		System.out.println("result{}"+result);
	}

  5. Effect See

   

/**
* user
*
* @author lyc
* @email [email protected]
* @date 2019-06-22
*/
@Data
@TableName("user")
public class UserEntity implements Serializable {
private static final long serialVersionUID = 1L;

/**
* 
*/
@TableId
private Integer id;
/**
* 名字
*/
private String name;
/**
* 年龄
*/
private Integer age;
}

  

Readers can achieve any template file, and then quickly generate, on the principle of this stuff, no chicken child difficulty, I wish you all a happy life.

 

Reproduced in: https: //www.cnblogs.com/lyc88/articles/11068536.html

Guess you like

Origin blog.csdn.net/weixin_34245749/article/details/93457402