使用过mybatis的generator生成model bean,但总觉得不尽如人意,自己折腾一个。基本的jdbc封装类见JDBC连接池封装 。
1.代码自动生成的配置
package dbTools;
import java.io.File;
public class CodeConfig
{
//包名
public static String PackageName="yzh.ssm";
//model包
public static String BeanPackageName=PackageName+".model";
//生成的java路径
public static String modelPath=BeanPackageName.replace(".", "\\");
//获得项目src目录的绝对路径
public static String getRoot(String path){
return new File(System.getProperty("user.dir")+"\\src",path).getAbsolutePath();
}
}
2.文件操作类FileHelper
package dbTools;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
/**
* 此类中封装一些常用的文件操作。 所有方法都是静态方法,不需要生成此类的实例, 为避免生成此类的实例,构造方法被申明为private类型的。
*
* @since 1.0
*/
public class FileHelper
{
/**
* 私有构造方法,防止类的实例化,因为工具类不需要实例化。
*/
private FileHelper()
{
}
/**
* 判断指定的文件是否存在。
*
* @param fileName
* 要判断的文件的文件名
* @return 存在时返回true,否则返回false。
* @since 1.0
*/
public static boolean isFileExist(String fileName)
{
return new File(fileName).isFile();
}
/**
* 创建指定的目录。 如果指定的目录的父目录不存在则创建其目录书上所有需要的父目录。 <b>注意:可能会在返回false的时候创建部分父目录。</b>
*
* @param file
* 要创建的目录
* @return 完全创建成功时返回true,否则返回false。
* @since 1.0
*/
public static boolean makeDirectory(File file)
{
File parent = file.getParentFile();
if (parent != null)
{
return parent.mkdirs();
}
return false;
}
/**
* 创建指定的目录。 如果指定的目录的父目录不存在则创建其目录书上所有需要的父目录。 <b>注意:可能会在返回false的时候创建部分父目录。</b>
*
* @param fileName
* 要创建的目录的目录名
* @return 完全创建成功时返回true,否则返回false。
* @since 1.0
*/
public static boolean makeDirectory(String fileName)
{
File file = new File(fileName);
return makeDirectory(file);
}
/**
* 将DOS/Windows格式的路径转换为UNIX/Linux格式的路径。
* 其实就是将路径中的"\"全部换为"/",因为在某些情况下我们转换为这种方式比较方便,
* 某中程度上说"/"比"\"更适合作为路径分隔符,而且DOS/Windows也将它当作路径分隔符。
*
* @param filePath
* 转换前的路径
* @return 转换后的路径
* @since 1.0
*/
public static String toUNIXpath(String filePath)
{
return filePath.replace('\\', '/');
}
/**
* 从文件名得到UNIX风格的文件绝对路径。
*
* @param fileName
* 文件名
* @return 对应的UNIX风格的文件路径
* @since 1.0
* @see #toUNIXpath(String filePath) toUNIXpath
*/
public static String getUNIXfilePath(String fileName)
{
File file = new File(fileName);
return toUNIXpath(file.getAbsolutePath());
}
/**
* 检查给定目录的存在性 保证指定的路径可用,如果指定的路径不存在,那么建立该路径,可以为多级路径
*
* @param path
* @return 真假值
* @since 1.0
*/
public static final boolean pathValidate(String path)
{
String[] arraypath = path.split("/");
String tmppath = "";
for (int i = 0; i < arraypath.length; i++)
{
tmppath += "/" + arraypath[i];
File d = new File(tmppath.substring(1));
if (!d.exists())
{ // 检查Sub目录是否存在
System.out.println(tmppath.substring(1));
if (!d.mkdir())
{
return false;
}
}
}
return true;
}
/**
* 根据内容生成文件
*
* @param path要生成文件的绝对路径
* ,
* @param 文件的内容
* 。
* @return 真假值
* @since 1.0
*/
public static final boolean genModuleTpl(String path, String modulecontent)
{
path = getUNIXfilePath(path);
String[] patharray = path.split("\\/");
String modulepath = "";
for (int i = 0; i < patharray.length - 1; i++)
{
modulepath += "/" + patharray[i];
}
File d = new File(modulepath.substring(1));
if (!d.exists())
{
if (!pathValidate(modulepath.substring(1)))
{
return false;
}
}
try
{
FileWriter fw = new FileWriter(path); // 建立FileWriter对象,并实例化fw
// 将字符串写入文件
fw.write(modulecontent);
fw.close();
} catch (IOException e)
{
System.out.println(e.getMessage());
}
return true;
}
}
3.Model代码生成
package dbTools;
import java.util.List;
public class ModelGenerator
{
static String rt = "\r\t";
// 创建Model类
public static void createModel(List<String> tablelist)
{
DBUtil dbConn = new DBUtil();
for (String tablename : tablelist)
{
List<String[]> colsList = dbConn.getColumnDatas(tablename);
StringBuilder sb = new StringBuilder();
sb.append("package " + CodeConfig.BeanPackageName + ";\n");
sb.append("import java.text.*;"+rt);
sb.append("public class " + toFirstUpperCase(tablename) + "{" + rt);
// 创建类,类名为表名首字母大写
for (String[] col : colsList)
{
//根据数据库字段备注生成成员变量注释
sb.append("//" + (col[2].length() > 0 ? col[2] : col[0]) + rt);
//声明成员变量
sb.append("private " + col[1] + " " + col[0] + ";" + rt);
// 创建get方法
sb.append("public " + col[1] + " get"
+ toFirstUpperCase(col[0]) + "()" + rt);
sb.append("{" + rt);
sb.append("\treturn this." + col[0] + ";" + rt);
sb.append("}" + rt);
//创建set方法
sb.append(
"public void set" + toFirstUpperCase(col[0]) + "(" + col[1] + " "
+ col[0] + ")" + rt);
sb.append("{" + rt);
sb.append("\tthis." + col[0] + "=" + col[0] + ";" + rt);
sb.append("}" + rt + rt);
}
//重写toString方法
sb.append("@Override" + rt);
sb.append("public String toString()" + rt);
sb.append("{" + rt);
sb.append("\tSimpleDateFormat sdf=new SimpleDateFormat(\"yyyy-MM-dd\");"+ rt);
sb.append("\treturn \"[\"+");
int n = 0;
for (String[] col : colsList)
{
if (!col[1].equals("java.util.Date"))
{
if (n < colsList.size() - 1)
{
sb.append("\" " + col[0] + "=\"+" + col[0] + "+");
}
else
{
sb.append("\" " + col[0] + "=\"+" + col[0]);
}
}
else
{
if (n < colsList.size() - 1)
{
sb.append("\" " + col[0] + "=\"+sdf.format(" + col[0]
+ ")+");
}
else
{
sb.append("\" " + col[0] + "=\"+sdf.format(" + col[0]
+ ")");
}
}
n++;
}
sb.append("+\"]\";" + rt);
sb.append("}" + rt + rt);
sb.append("\n}" + rt);
// 创建文件
FileHelper.genModuleTpl(
CodeConfig.getRoot(CodeConfig.modelPath + "\\"
+ toFirstUpperCase(tablename)+ ".java"),
sb.toString());
System.out.println(
CodeConfig.BeanPackageName + ": " + tablename + " 创建成功!");
}
}
/**
* 首字母大写
* @return
*/
public static String toFirstUpperCase(String s)
{
return s.substring(0, 1).toUpperCase()+ s.substring(1);
}
}
4.测试
数据库sql语句:
CREATE DATABASE /*!32312 IF NOT EXISTS*/`student` /*!40100 DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci */;
USE `student`;
/*Table structure for table `stu` */
DROP TABLE IF EXISTS `stu`;
CREATE TABLE `stu` (
`stuId` int(11) NOT NULL auto_increment COMMENT '编号',
`stuName` varchar(100) collate utf8_unicode_ci default NULL COMMENT '姓名',
`stuAge` int(11) default NULL COMMENT '年龄',
`stuMajor` varchar(100) collate utf8_unicode_ci default NULL COMMENT '专业',
PRIMARY KEY (`stuId`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*Data for the table `stu` */
insert into `stu`(`stuId`,`stuName`,`stuAge`,`stuMajor`) values (1,'aaa',20,'计算机'),(2,'bbb',21,'计算机'),(3,'ccc',19,'信科'),(4,'d',23,'电商'),(5,'eee',21,'信科'),(6,'fff',22,'信科'),(7,'ggg',20,'信科'),(8,'hhh',19,'计算机'),(9,'kkk',20,'电商'),(10,'mmm',21,'电商');
/*Table structure for table `user` */
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`id` int(11) NOT NULL auto_increment,
`user_name` varchar(100) collate utf8_unicode_ci NOT NULL,
`password` varchar(100) collate utf8_unicode_ci NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*Data for the table `user` */
insert into `user`(`id`,`user_name`,`password`) values (1,'yzh','yzh');
测试方法
package dbTools;
import java.util.List;
public class Test
{
public static void main(String[] args)
{
DBUtil db=new DBUtil();
List<String> tablelist=db.getTables();
ModelGenerator.createModel(tablelist);
}
}
生成的User类代码:
package yzh.ssm.model;
import java.text.*;
public class User{
//id
private Integer id;
public Integer getId()
{
return this.id;
}
public void setId(Integer id)
{
this.id=id;
}
//user_name
private String user_name;
public String getUser_name()
{
return this.user_name;
}
public void setUser_name(String user_name)
{
this.user_name=user_name;
}
//password
private String password;
public String getPassword()
{
return this.password;
}
public void setPassword(String password)
{
this.password=password;
}
@Override
public String toString()
{
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
return "["+" id="+id+" user_name="+user_name+" password="+password+"]";
}
}
生成的Stu类代码:
package yzh.ssm.model;
import java.text.*;
public class Stu{
//编号
private Integer stuId;
public Integer getStuId()
{
return this.stuId;
}
public void setStuId(Integer stuId)
{
this.stuId=stuId;
}
//姓名
private String stuName;
public String getStuName()
{
return this.stuName;
}
public void setStuName(String stuName)
{
this.stuName=stuName;
}
//年龄
private Integer stuAge;
public Integer getStuAge()
{
return this.stuAge;
}
public void setStuAge(Integer stuAge)
{
this.stuAge=stuAge;
}
//专业
private String stuMajor;
public String getStuMajor()
{
return this.stuMajor;
}
public void setStuMajor(String stuMajor)
{
this.stuMajor=stuMajor;
}
@Override
public String toString()
{
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
return "["+" stuId="+stuId+" stuName="+stuName+" stuAge="+stuAge+" stuMajor="+stuMajor+"]";
}
}