导入jar包,修改pom.xml
新建resources文件夹和java文件夹
resources文件夹用于存放ftl模板文件
java文件夹用于存放java文件
再resources文件夹新建一个ftl模板
hello.ftl
Document
${name}
<#--这是模板遍历-->
<#list textlist as item>
${item}
#list>
新建测试类进行模板生成测试
import freemarker.template.Configuration;
import freemarker.template.Template;
import java.io.*;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class htmlDemo {
//与hibernate初识化相似
public Configuration configuration=new Configuration(Configuration.getVersion());
//要使用freemarker模板要先初始化
public void init(){
try {
//加载配置文件路径,即读取resources文件夹下的ftl模板,注意若路径中包含有中文,请写成下面这种格式
String path=URLDecoder.decode(this.getClass().getClassLoader().getResource("").getPath(),"utf-8");
//开始正式初始化
configuration.setDirectoryForTemplateLoading(new File(path));
} catch (IOException e) {
e.printStackTrace();
}
}
public void process(String tempname,String pathname){
try {
//获得模板,传进来的ftl模板的名字
Template template=configuration.getTemplate(tempname);
Map map=new HashMap();
//这里的name的对应模板内的${name}
map.put("name","Tom");
//放入集合对象进map ${textlist}
List ll=new ArrayList<>();
ll.add("这是");
ll.add("模板遍历");
ll.add("集合还是要放进map里面");
map.put("textlist",ll);
//文件读取的io流,用于写入内容并创建此通过模板生成的文件
FileOutputStream fileOutputStream=new FileOutputStream(pathname);
OutputStreamWriter outputStream=new OutputStreamWriter(fileOutputStream);
//通过方法把内容输入进模板内
template.process(map,outputStream);
} catch (Exception e) {
e.printStackTrace();
}
}
//写main方法测试
public static void main(String[] args) {
htmlDemo htmlDemo=new htmlDemo();
htmlDemo.init();
//注意,调用的是本类的方法,第一个参数即模板的完整名字,第二个是通过模板生成的文件路径
htmlDemo.process("hello.ftl","D://aa.html");
}
}
首先要带入连接mysql的jar包,跟JDBC差不多
mysql
mysql-connector-java
5.1.10
org.freemarker
freemarker
2.3.23
Column是存放表的列属性类
CreatePOJO是创建实体类的方法类
DBHelper是连接数据库的工具类
FreeMarkerUtil是自动生成模板的工具类
Generator是写静态属性的,暂时用于写好JDBC的参数
GetTables是调用DBHelper来获取所有的表其列的工具类
Tables是存放数据库中表属性类
StringUtils 字符串工具类 用于修改字符串首字母大写,去除下划线等
先按步骤从简单到困难
1.创建Generator(静态属性参数类)
package com.bdqn.util;
public class Generator {
public static String DRIVER="com.mysql.jdbc.Driver";
public static String URL="jdbc:mysql://127.0.0.1:3306/ebank?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=UTC";
public static String USERNAME="root";
public static String PASSWORD="123456";
}
2.DBHelper(JDBC连接工具类) 调用Generator的静态参数
package com.bdqn.util;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
public class DBHelper {
private static Connection connection;
public static Connection getConnection(){
try {
Class.forName(Generator.DRIVER);
connection=DriverManager.getConnection(Generator.URL,Generator.USERNAME,Generator.PASSWORD);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return connection;
}
public static void closeConnection(Connection connection, ResultSet rs){
try {
if (rs!=null){
rs.close();
}
if (connection!=null){
connection.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
3.创建Column类 存放表内每一列中属性,入列名 类型
package com.bdqn.util;
public class Column {
//列名
private String columnName;
//修改后的列名
private String updateColumnName;
//数据库中的类型名
private String dbType;
//处理后对应java的类型名
private String javaType;
public String getUpdateColumnName() {
return updateColumnName;
}
public void setUpdateColumnName(String updateColumnName) {
this.updateColumnName = updateColumnName;
}
public String getColumnName() {
return columnName;
}
public void setColumnName(String columnName) {
this.columnName = columnName;
}
public String getDbType() {
return dbType;
}
public void setDbType(String dbType) {
this.dbType = dbType;
}
public String getJavaType() {
return javaType;
}
public void setJavaType(String javaType) {
this.javaType = javaType;
}
}
4.创建tables类 存放数据库中表内的属性 如表名 还有一个是存放java的类名(ClassName) 这种表包含的列信息
package com.bdqn.util;
import java.util.ArrayList;
import java.util.List;
public class Tables {
private String tableName;
private String tableClassName;
private List columnlist=new ArrayList<>();
public String getTableName() {
return tableName;
}
public void setTableName(String tableName) {
this.tableName = tableName;
}
public String getTableClassName() {
return tableClassName;
}
public void setTableClassName(String tableClassName) {
this.tableClassName = tableClassName;
}
public List getColumnlist() {
return columnlist;
}
public void setColumnlist(List columnlist) {
this.columnlist = columnlist;
}
}
5.创建StringUtils字符串工具类 用于给数据库中获得的表名列名信息修改成java格式的工具类
package com.bdqn.util;
/**
* Created by zezhong.shang on 17-6-2.
*/
public class StringUtils {
/**
* ijλ����ĸ��д
*
* @param name
* @param indx
* @return
*/
public static String captureName(String name, int indx) {
name = name.substring(0, indx) + name.substring(indx, indx + 1).toUpperCase() + name.substring(indx + 1);
return name;
}
/**
* ����ĸ��д
*
* @param name
* @return
*/
public static String captureName(String name) {
name = name.substring(0, 1).toUpperCase() + name.substring(1);
return name;
}
/***
* ����ĸСд
*
* @param name
* @return
*/
public static String lowerName(String name) {
name = name.substring(0, 1).toLowerCase() + name.substring(1);
return name;
}
/***
* ȥ���»��� �����շ�ԭ�����ת��
*
* @return
*/
public static String putOffUnderline(String columnName) {
StringBuffer fieldNameBuffer = null;
String tempNameArray[] = columnName.split("_");
for (int i = 0; i < tempNameArray.length; i++) {
if (i == 0) {
fieldNameBuffer = new StringBuffer(tempNameArray[i]);
} else {
fieldNameBuffer.append(captureName(tempNameArray[i]));
}
}
return fieldNameBuffer.toString();
}
public static void main(String[] args) {
String a = putOffUnderline("a_bccc_d");
System.out.println(a);
}
}
6.创建GetTables类 前面创建的类都是为后面这几个类使用的 从数据库中获取表和列信息并返回成集合
package com.bdqn.util;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
public class GetTables {
//获得数据库中所有表名的方法
public List gettables(){
//JDBC获得连接
Connection conn=DBHelper.getConnection();
//返回的list
List ll=new ArrayList<>();
try {
//调用这个方法就能获取表和列以及对应信息
DatabaseMetaData dbmd=conn.getMetaData();
//固定写法,获得游标
ResultSet rs=dbmd.getTables(null,null,null,new String[]{"TABLE"});
while (rs.next()){
//获取这个数据中所有的表名
String tableName=rs.getString("TABLE_NAME");
Tables tables=new Tables();
//添加表名
tables.setTableName(tableName);
//添加类名(处理后的类名,类名大写,下划线去掉)
tables.setTableClassName(StringUtils.putOffUnderline(StringUtils.captureName(tableName)));
//实例化方便调用本类的方法
GetTables getTables=new GetTables();
//调用下面查看列的方法,并添加进tables内
tables.setColumnlist(getTables.getColumnName(tableName));
ll.add(tables);
}
//个人习惯,关连接
DBHelper.closeConnection(conn,rs);
} catch (SQLException e) {
e.printStackTrace();
}
return ll;
}
//获得表中的列的信息
public List getColumnName(String tablename){
List ll=new ArrayList<>();
try {
Connection conn=DBHelper.getConnection();
DatabaseMetaData dbmd=conn.getMetaData();
//固定参数写法,传入表名获取当前表的所有列信息
ResultSet rs=dbmd.getColumns(null,"%",tablename,"%");
while (rs.next()){
String columnName=rs.getString("COLUMN_NAME");
String columnType=rs.getString("TYPE_NAME");
Column column=new Column();
//添加列名
column.setColumnName(StringUtils.captureName(columnName));
//添加处理后的列名
column.setUpdateColumnName(StringUtils.putOffUnderline(StringUtils.lowerName(columnName)));
//添加数据库类型
column.setDbType(columnType);
//添加java类型
column.setJavaType(GetTables.switchType(columnType));
//把获得列对象放进集合内
ll.add(column);
}
} catch (SQLException e) {
e.printStackTrace();
}
return ll;
}
//把数据库类型转换成java类型
public static String switchType(String cloumnType){
String fieldType=null;
if(cloumnType.equals("VARCHAR")){
fieldType="String";
}else if(cloumnType.equals("BIGINT")){
fieldType="Long";
}else if(cloumnType.equals("INT")){
fieldType="Integer";
}else if(cloumnType.equals("DATETIME")){
fieldType="Date";
}else{
fieldType="String";
}
return fieldType;
}
}
7.创建FreeMarkerUtil类 通过上面的GetTables类方法已经获得了数据库中每一张表的详细信息,现在要把它输入到模板中
package com.bdqn.util;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Map;
public class FreeMarkerUtil {
Configuration configuration=new Configuration(Configuration.getVersion());
//初始化方法
public void init(){
try {
//解析路径是中文乱码时找不到路径的错误
String path= URLDecoder.decode(this.getClass().getClassLoader().getResource("").getPath(),"UTF-8");
configuration.setDirectoryForTemplateLoading(new File(path));
} catch (IOException e) {
e.printStackTrace();
}
}
//把获得的信息写入到模板中
public void createFile(String template, String pathname, Tables ll){
try {
Template template1=configuration.getTemplate(template);
Map map=new HashMap();
//传入内容到模板
map.put("tablelist",ll);
FileOutputStream fs=new FileOutputStream(pathname);
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fs);
template1.process(map,outputStreamWriter);
} catch (IOException e) {
e.printStackTrace();
} catch (TemplateException e) {
e.printStackTrace();
}
}
}
对应的模板 在resources文件夹内
注意,需要修改的是package 包的路径,这就是对应实体类的模板
package com.bdqn.pojo;
import java.util.Date;
import java.io.Serializable;
public class ${tablelist.tableClassName} implements Serializable{
<#list tablelist.columnlist as items>
private ${items.javaType} ${items.updateColumnName};
#list>
<#list tablelist.columnlist as items>
public void set${items.columnName}(${items.javaType} ${items.updateColumnName}){
this.${items.updateColumnName} = ${items.updateColumnName};
}
public ${items.javaType} get${items.columnName}(){
return ${items.updateColumnName};
}
#list>
}
最后创建CreatePOJO类 ,里面直接写main方法来创建实体类了
package com.bdqn.util;
import java.util.List;
public class CreatePOJO {
public static void main(String[] args) {
//实例化此前获取表和列信息的类,并获取信息
GetTables getTables=new GetTables();
List ll=getTables.gettables();
//实例化模板类,记得必须初始化
FreeMarkerUtil freeMarkerUtil=new FreeMarkerUtil();
freeMarkerUtil.init();
//这是创建后的实体类存放地址
String url="D://java传输文件安置处//FreeMarkerDemo//pokoDemo2//src//main//java//com//bdqn//pojo//";
for (Tables tt:ll) {
//把获得的信息写入到指定模板内,开始生成实体类
freeMarkerUtil.createFile("pojo.ftl", url+tt.getTableClassName()+".java",tt);
}
}
}
上面就是自动创建实体类的全部过程。后续会更新创建mybatis的自动生成dao层模板
更新:处理特殊字符串时的写法
#获取下标及最后一项
service层模板
package com.bdqn.service;
import com.bdqn.dao.${obj.tableClassName}Mapper;
import com.bdqn.pojo.${obj.tableClassName};
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class ${obj.tableClassName}Service {
@Autowired(required = false)
private ${obj.tableClassName}Mapper ${obj.tableName}Mapper;
public ${obj.tableClassName}Mapper get${obj.tableClassName}Mapper() {
return ${obj.tableName}Mapper;
}
public void set${obj.tableClassName}Mapper(${obj.tableClassName}Mapper ${obj.tableClassName}Mapper) {
this.${obj.tableName}Mapper = ${obj.tableName}Mapper;
}
public List<${obj.tableClassName}> findAll${obj.tableClassName}(){return ${obj.tableName}Mapper.findAll${obj.tableClassName}();}
public List<${obj.tableClassName}> find${obj.tableClassName}ById(int id){return ${obj.tableName}Mapper.find${obj.tableClassName}ById(id);}
public int add${obj.tableClassName}(${obj.tableClassName} ${obj.tableName}){return ${obj.tableName}Mapper.add${obj.tableClassName}(${obj.tableName});}
public int del${obj.tableClassName}ById(int id){return ${obj.tableName}Mapper.del${obj.tableClassName}ById(id);}
public int update${obj.tableClassName}(${obj.tableClassName} ${obj.tableName}){return ${obj.tableName}Mapper.update${obj.tableClassName}(${obj.tableName});}
}
controller层模板
package com.bdqn.controller;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.bdqn.pojo.${obj.tableClassName};
import com.bdqn.service.${obj.tableClassName}Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/${obj.tableClassName}Controller")
public class ${obj.tableClassName}Controller {
@Autowired(required = false)
private ${obj.tableClassName}Service ${obj.tableName}Service;
public ${obj.tableClassName}Service get${obj.tableClassName}Service() {
return ${obj.tableName}Service;
}
public void set${obj.tableClassName}Service(${obj.tableClassName}Service ${obj.tableName}Service) {
this.${obj.tableName}Service = ${obj.tableName}Service;
}
@RequestMapping(value="/findAll${obj.tableClassName}",method = RequestMethod.GET)
public String findAll${obj.tableClassName}(){
return JSONArray.toJSONString(${obj.tableName}Service.findAll${obj.tableClassName}());
}
@RequestMapping(value="/find${obj.tableClassName}ById",method = RequestMethod.GET)
public String find${obj.tableClassName}ById(@RequestParam("id") int id){
return JSON.toJSONString(${obj.tableName}Service.del${obj.tableClassName}ById(id));
}
@RequestMapping(value="/add${obj.tableClassName}",method = RequestMethod.POST)
public int add${obj.tableClassName}(@RequestBody ${obj.tableClassName} ${obj.tableName}){return ${obj.tableName}Service.add${obj.tableClassName}(${obj.tableName});}
@RequestMapping(value="/del${obj.tableClassName}ById",method = RequestMethod.GET)
public int del${obj.tableClassName}ById(@RequestParam("id") int id){return ${obj.tableName}Service.del${obj.tableClassName}ById(id);}
@RequestMapping(value="/update${obj.tableClassName}",method = RequestMethod.POST)
public int update${obj.tableClassName}(@RequestBody ${obj.tableClassName} ${obj.tableName}){return ${obj.tableName}Service.update${obj.tableClassName}(${obj.tableName});}
}