代码自动生成 数据库表字段生成mybaties 映射配置文件**mapper.xml
下面试freemarker工具类
- import java.io.BufferedWriter;
- import java.io.File;
- import java.io.FileOutputStream;
- import java.io.IOException;
- import java.io.OutputStreamWriter;
- import java.io.PrintWriter;
- import java.io.Writer;
- import java.util.Locale;
- import java.util.Map;
- import freemarker.template.Configuration;
- import freemarker.template.Template;
- import freemarker.template.TemplateException;
- public class Freemarker {
- /**
- * 打印到控制台(测试)
- * @param ftlName
- */
- public static void print(String ftlName, Map<String,Object> root, String ftlPath) throws Exception{
- try {
- Template temp = getTemplate(ftlName, ftlPath); //通过Template可以将模板文件输出到相应的流
- temp.process(root, new PrintWriter(System.out));
- } catch (TemplateException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- /**
- * 输出到输出到文件
- * @param ftlName ftl文件
- * @param root 传入的map
- * @param outFile 输出后的文件全部路径
- * @param filePath 输出前的文件上部路径
- */
- public static void printFile(String ftlName, Map<String,Object> root, String outFile, String filePath, String ftlPath) throws Exception{
- try {
- File file = new File( filePath + outFile);
- if(!file.getParentFile().exists()){ //判断有没有父路径,就是判断文件整个路径是否存�?
- file.getParentFile().mkdirs(); //不存在就全部创建
- }
- Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "utf-8"));
- Template template = getTemplate(ftlName, ftlPath);
- template.process(root, out); //模版输出
- out.flush();
- out.close();
- } catch (TemplateException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- /**
- * 通过文件名加载模�?
- * @param ftlName
- */
- public static Template getTemplate(String ftlName, String ftlPath) throws Exception{
- try {
- Configuration cfg = new Configuration(); //通过Freemaker的Configuration读取相应的ftl
- cfg.setEncoding(Locale.CHINA, "utf-8");
- cfg.setDirectoryForTemplateLoading(new File(ftlPath)); //设定去哪里读取相应的ftl模板文件
- Template temp = cfg.getTemplate(ftlName); //在模板文件目录中找到名称为name的文�?
- return temp;
- } catch (IOException e) {
- e.printStackTrace();
- }
- return null;
- }
- }
- public class Student {
- private String id;
- private String name;
- public String getId() {
- return id;
- }
- public void setId(String id) {
- this.id = id;
- }
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
- }
- <?xml version="1.0" encoding="UTF-8"?>
- <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
- <mapper namespace="${objectName}Mapper">
- <!-- 新增-->
- <insert id="save" parameterType="${pack}">
- insert into ${table}(
- <#list fieldList as var>
- ${var},
- </#list>
- ${id}
- ) values (
- <#list fieldList as var>
- ${r"#{"}${var}${r"}"},
- </#list>
- ${r"#{"}${id}${r"}"}
- )
- </insert>
- <!-- 删除-->
- <delete id="delete" parameterType="${pack}">
- delete from ${table}
- where
- ${id} = ${r"#{"}${id}${r"}"}
- </delete>
- <!-- 修改 -->
- <update id="edit" parameterType="${pack}">
- update ${table}
- set
- <#list fieldList as var>
- <#if var??>
- ${var} = ${r"#{"}${var}${r"}"},
- </#if>
- </#list>
- where
- ${id} = ${r"#{"}${id}${r"}"}
- </update>
- <!-- 通过ID获取数据 -->
- <select id="findById" parameterType="java.lang.String" resultType="${pack}">
- select
- <#list fieldList as var>
- ${var},
- </#list>
- ${id}
- from
- ${table}
- where
- ${id} = ${r"#{"}${id}${r"}"}
- </select>
- <!-- 列表(全部) -->
- <select id="listAll" resultType="${pack}">
- select
- <#list fieldList as var>
- a.${var},
- </#list>
- a.${id}
- from
- ${table} a
- </select>
- </mapper>
查找数据库表字段的工具类
- import java.io.BufferedWriter;
- import java.io.File;
- import java.io.FileWriter;
- import java.io.IOException;
- import java.sql.Connection;
- import java.sql.DriverManager;
- import java.sql.PreparedStatement;
- import java.sql.ResultSet;
- import java.sql.ResultSetMetaData;
- import java.sql.SQLException;
- import java.util.ArrayList;
- import java.util.List;
- public class ReflectBean {
- private Connection connection;
- /*mysql url的连接字符串*/
- private static String url = "jdbc:mysql://127.0.0.1:3306/wechat?useUnicode=true&characterEncoding=UTF-8";
- //账号
- private static String user = "root";
- //密码
- private static String password = "123456";
- //mysql jdbc的java包驱动字符串
- private String driverClassName = "com.mysql.jdbc.Driver";
- //数据库中的表名
- private String table;
- public String getTable() {
- return table;
- }
- public void setTable(String table) {
- this.table = table;
- }
- //数据库的列名称
- private String[] colnames; // 列名数组
- //列名类型数组
- private String[] colTypes;
- public String[] getColnames() {
- return colnames;
- }
- public void setColnames(String[] colnames) {
- this.colnames = colnames;
- }
- public String[] getColTypes() {
- return colTypes;
- }
- public void setColTypes(String[] colTypes) {
- this.colTypes = colTypes;
- }
- public Connection getConnection() {
- return connection;
- }
- public void setConnection(Connection connection) {
- this.connection = connection;
- }
- public ReflectBean(){
- try {//驱动注册
- Class.forName(driverClassName);
- if (connection == null || connection.isClosed())
- //获得链接
- connection = DriverManager.getConnection(url, user, password);
- } catch (ClassNotFoundException ex) {
- ex.printStackTrace();
- System.out.println("Oh,not");
- } catch (SQLException e) {
- e.printStackTrace();
- System.out.println("Oh,not");
- }
- }
- public List<String> doAction(){
- String sql = "select * from "+table;
- List<String> list = new ArrayList<String>();
- try {
- PreparedStatement statement = connection.prepareStatement(sql);
- //获取数据库的元数据
- ResultSetMetaData metadata = statement.getMetaData();
- ResultSet rs = connection.getMetaData().getPrimaryKeys(null, null, table);
- String id = "";
- //获取组键字段
- if(rs.next()){
- id = rs.getString(4);
- }
- //数据库的字段个数
- int len = metadata.getColumnCount();
- //字段名称
- colnames = new String[len+1];
- //字段类型 --->已经转化为java中的类名称了
- colTypes = new String[len+1];
- for(int i= 1;i<=len;i++){
- //System.out.println(metadata.getColumnName(i)+":"+metadata.getColumnTypeName(i)+":"+sqlType2JavaType(metadata.getColumnTypeName(i).toLowerCase())+":"+metadata.getColumnDisplaySize(i));
- //metadata.getColumnDisplaySize(i);
- colnames[i] = metadata.getColumnName(i); //获取字段名称
- list.add( colnames[i]);
- colTypes[i] = sqlType2JavaType(metadata.getColumnTypeName(i)); //获取字段类型
- }
- list.add(id);
- } catch (SQLException e) {
- e.printStackTrace();
- }
- return list;
- }
- /*
- * mysql的字段类型转化为java的类型*/
- private String sqlType2JavaType(String sqlType) {
- if(sqlType.equalsIgnoreCase("bit")){
- return "boolean";
- }else if(sqlType.equalsIgnoreCase("tinyint")){
- return "byte";
- }else if(sqlType.equalsIgnoreCase("smallint")){
- return "short";
- }else if(sqlType.equalsIgnoreCase("int")){
- return "int";
- }else if(sqlType.equalsIgnoreCase("bigint")){
- return "long";
- }else if(sqlType.equalsIgnoreCase("float")){
- return "float";
- }else if(sqlType.equalsIgnoreCase("decimal") || sqlType.equalsIgnoreCase("numeric")
- || sqlType.equalsIgnoreCase("real") || sqlType.equalsIgnoreCase("money")
- || sqlType.equalsIgnoreCase("smallmoney")){
- return "double";
- }else if(sqlType.equalsIgnoreCase("varchar") || sqlType.equalsIgnoreCase("char")
- || sqlType.equalsIgnoreCase("nvarchar") || sqlType.equalsIgnoreCase("nchar")
- || sqlType.equalsIgnoreCase("text")){
- return "String";
- }else if(sqlType.equalsIgnoreCase("datetime") ||sqlType.equalsIgnoreCase("date")){
- return "Date";
- }else if(sqlType.equalsIgnoreCase("image")){
- return "Blod";
- }else if(sqlType.equalsIgnoreCase("timestamp")){
- return "Timestamp";
- }
- return null;
- }
- /*获取整个类的字符串并且输出为java文件
- * */
- public StringBuffer getClassStr(){
- //输出的类字符串
- StringBuffer str = new StringBuffer("");
- //获取表类型和表名的字段名
- this.doAction();
- //校验
- if(null == colnames && null == colTypes) return null;
- //拼接
- str.append("public class "+GetTuoFeng(table)+" {\r\n");
- //拼接属性
- for(int index=1; index < colnames.length ; index++){
- str.append(getAttrbuteString(colnames[index],colTypes[index]));
- }
- //拼接get,Set方法
- for(int index=1; index < colnames.length ; index++){
- str.append(getGetMethodString(colnames[index],colTypes[index]));
- str.append(getSetMethodString(colnames[index],colTypes[index]));
- }
- str.append("}\r\n");
- //输出到文件中
- File file = new File("E:/mengwx/【源码】mysql版本_spring4.0/FHMYSQL/src/com/fh/entity/"+GetTuoFeng(table)+".java");
- BufferedWriter write = null;
- try {
- write = new BufferedWriter(new FileWriter(file));
- write.write(str.toString());
- write.close();
- } catch (IOException e) {
- e.printStackTrace();
- if (write != null)
- try {
- write.close();
- } catch (IOException e1) {
- e1.printStackTrace();
- }
- }
- return str;
- }
- /*
- * 获取字段字符串*/
- public StringBuffer getAttrbuteString(String name, String type) {
- if(!check(name,type)) {
- System.out.println("类中有属性或者类型为空");
- return null;
- };
- String format = String.format(" private %s %s;\n\r", new String[]{type,name});
- return new StringBuffer(format);
- }
- /*
- * 校验name和type是否合法*/
- public boolean check(String name, String type) {
- if("".equals(name) || name == null || name.trim().length() ==0){
- return false;
- }
- if("".equals(type) || type == null || type.trim().length() ==0){
- return false;
- }
- return true;
- }
- /*
- * 获取get方法字符串*/
- private StringBuffer getGetMethodString(String name, String type) {
- if(!check(name,type)) {
- System.out.println("类中有属性或者类型为空");
- return null;
- };
- String Methodname = "get"+GetTuoFeng(name);
- String format = String.format(" public %s %s(){\n\r", new Object[]{type,Methodname});
- format += String.format(" return this.%s;\r\n", new Object[]{name});
- format += " }\r\n";
- return new StringBuffer(format);
- }
- //将名称首字符大写
- private String GetTuoFeng(String name) {
- name = name.trim();
- if(name.length() > 1){
- name = name.substring(0, 1).toUpperCase()+name.substring(1);
- }else
- {
- name = name.toUpperCase();
- }
- return name;
- }
- /*
- * 获取字段的get方法字符串*/
- private Object getSetMethodString(String name, String type) {
- if(!check(name,type)) {
- System.out.println("类中有属性或者类型为空");
- return null;
- };
- String Methodname = "set"+GetTuoFeng(name);
- String format = String.format(" public void %s(%s %s){\n\r", new Object[]{Methodname,type,name});
- format += String.format(" this.%s = %s;\r\n", new Object[]{name,name});
- format += " }\r\n";
- return new StringBuffer(format);
- }
- public static void main(String[] args) {
- ReflectBean bean = new ReflectBean();
- System.err.println(bean.getClassStr());
- }
- }
生成mapper.xml的工具类
- import java.util.Date;
- import java.util.HashMap;
- import java.util.List;
- import java.util.Map;
- import com.mengwx.entiy.Student;
- import com.mengwx.util.Freemarker;
- import com.mengwx.util.ReflectBean;
- public class CreateCodeController{
- /**
- * 生成代码
- */
- public static void proCode(Object object,String table) throws Exception{
- String objectName = object.getClass().getSimpleName();
- String pack = object.getClass().getName();
- ReflectBean re = new ReflectBean();
- re.setTable(table);
- List<String> list = re.doAction();
- Map<String,Object> root = new HashMap<String,Object>();
- String id = "";
- if(list.size()>=1){//创建数据模型
- id = list.get(list.size()-1);
- }
- root.put("packageName", objectName);
- root.put("pack", pack); //包名
- root.put("objectName", objectName); //类名
- root.put("objectNameLower", objectName.toLowerCase()); //类名(全小写)
- root.put("objectNameUpper", objectName.toUpperCase()); //类名(全大写)
- root.put("nowDate", new Date()); //当前日期
- root.put("table", table);
- root.put("id", list.get(list.size()-1));
- list.remove(list.size()-1);
- list.remove(id);
- root.put("fieldList", list);
- String filePath = "C:/Users/huxf/workspace/createcode/src/com/mengwx/code/"; //存放路径
- String ftlPath = "C:/Users/huxf/workspace/createcode/src/com/mengwx/ftl"; //ftl路径
- /*生成mybatis xml*/
- Freemarker.printFile("mapperMysqlTemplate.ftl", root, ""+Student.class.getSimpleName()+"Mapper.xml", filePath, ftlPath);
- }
- public static void main(String[] args) throws Exception {
- proCode(new Student(),"student");
- }
- }
生成的mapper.xml文件
- <?xml version="1.0" encoding="UTF-8"?>
- <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
- <mapper namespace="StudentMapper">
- <!-- 新增-->
- <insert id="save" parameterType="com.mengwx.entiy.Student">
- insert into student(
- name,
- id
- ) values (
- #{name},
- #{id}
- )
- </insert>
- <!-- 删除-->
- <delete id="delete" parameterType="com.mengwx.entiy.Student">
- delete from student
- where
- id = #{id}
- </delete>
- <!-- 修改 -->
- <update id="edit" parameterType="com.mengwx.entiy.Student">
- update student
- set
- name = #{name},
- where
- id = #{id}
- </update>
- <!-- 通过ID获取数据 -->
- <select id="findById" parameterType="java.lang.String" resultType="com.mengwx.entiy.Student">
- select
- name,
- id
- from
- student
- where
- id = #{id}
- </select>
- <!-- 列表(全部) -->
- <select id="listAll" resultType="com.mengwx.entiy.Student">
- select
- a.name,
- a.id
- from
- student a
- </select>
- </mapper>
项目目录结构 StudentMapper.xml是生成的文件