一、引言
在用过hibernate自动生成后,对于不断写pojo类比较厌烦,但现在许多用的框架并没有带自动生成功能,于是试着写了一个自动生成POJO的工具。
二、步骤
1、建立工程,要求jdk的版本必须在1.7以上。工程结构如下、
:
2、首先连接数据库,这毋庸置言的,博主用的数据库是sqlserver2008。下面是properties的配置:
jdbc.properties:
</pre><pre name="code" class="plain">driverclass=com.microsoft.sqlserver.jdbc.SQLServerDriver
jdbcUrl=jdbc:sqlserver://localhost:1433;DatabaseName=
databasename=test
user=sa
password=erry
</pre><span style="white-space:pre"></span> <span style="font-size:18px">3、建立数据库的连接DbCreatePOJO.java</span><p></p><p><span style="font-size:18px"><span style="white-space:pre"></span></span></p><pre name="code" class="java">static {
PropertiesReader pr = new PropertiesReader("jdbc.properties", "utf-8");
DATABASENAME = (String) pr.getProperties().get("databasename");
URL = (String) pr.getProperties().get("jdbcUrl")+DATABASENAME;
JDBC_DRIVER =(String) pr.getProperties().get("driverclass");
USER_NAME = (String) pr.getProperties().get("user");
PASSWORD = (String) pr.getProperties().get("password");
PACKAGENAME = "com.admin.bean";
}
/**
* 获得连接
* @return
*/
public static Connection getConnection() {
try {
Class.forName(JDBC_DRIVER);
conn = DriverManager.getConnection(URL, USER_NAME, PASSWORD);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return conn;
}
4、连接成功后,我们获取数据库中的表名和各个表中列的名称和属性,注意的是mysql和oracle、sqlserver对表名的查询方法都不同。
<span style="white-space:pre"> </span>String sql = "SELECT Name FROM test..SysObjects Where XType='U' ORDER BY Name";//sqlserver查询表名
<span style="white-space:pre"> </span>String sql = "select table_name from user_tables";//oracle 查询用户表(没有系统表)
<span style="white-space:pre"> </span>String sql = "select column_name,data_type from information_schema.columns where table_name = 表名";
<span style="white-space:pre"> select column_name,data_type from user_tab_columns where table_name='</span>表名<span style="white-space:pre">'</span>;//oracle
5、获取到表名和列名,然后建立名称规则MyStringUtils.java:
/**
* 类名定义
* @return
*/
public static String StringToCamleCaseClassName(String str){
StringBuffer stringbf = new StringBuffer();
Matcher m = Pattern
.compile("([a-z])([a-z]*)", Pattern.CASE_INSENSITIVE).matcher(
str);
while (m.find()) {
m.appendReplacement(stringbf, m.group(1).toUpperCase()
+ m.group(2).toLowerCase());
}
return m.appendTail(stringbf).toString().replace("_","").replace(" ","");
}
/**
* 类属性定
* @param str
* @return
*/
public static String StringToCamleCaseClassProte(String str){
StringBuffer stringbf = new StringBuffer();
Matcher m = Pattern
.compile("([a-z])([a-z]*)", Pattern.CASE_INSENSITIVE).matcher(
str);
while (m.find()) {
m.appendReplacement(stringbf, m.group(1).toUpperCase()
+ m.group(2).toLowerCase());
}
String result = m.appendTail(stringbf).toString().replace("_","").replace(" ","");
return result.replaceFirst(result.substring(0,1),result.substring(0,1).toLowerCase());
}
public static String DatabasetypeConver(String type){
switch (type) {
case "int":;
case "bit":;
case "smallint":;
case "tinyint":
return "Integer";
case "Float":;
case "real":;
return "float";
case "numeric":;
return "Double";
case "datetime":;
case "smalldatetime":;
return "Date";
default:
return "String";
}
}
6、这是开始进行文件的生成
DbCreatePOJO.java:
public static void CreatePojo(){
try {
getConnection();
List<String> tables = getAllTables();
for (int i = 0; i < tables.size(); i++) {
String path = System.getProperty("user.dir")+"/src/"+PACKAGENAME.replace(".", "/");
System.out.println(path);
File createFolder = new File(path);
//路径不存在,生成文件夹
if (!createFolder.exists()) {
createFolder.mkdirs();
}
String entityString = CreateEntityString(tables.get(i).trim());
File entity = new File(createFolder.getAbsolutePath()+"/"+MyStringUtil.StringToCaml<span style="white-space:pre"> </span>eCaseClassName(tables.get(i))+".java");
if (!entity.exists())
{
//写入文件
BufferedWriter out = new BufferedWriter(new FileWriter(entity, true));
out.write(entityString);
out.close();
out = null;
entity = null;
}
}
closeConnection();
System.out.println("生成成功");
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 生成字段 声明
* @param connection
* @param tableName
* @return
*/
private static String CreateEntityString(String tableName){
String tableConverName = MyStringUtil.StringToCamleCaseClassName(tableName);
StringBuffer result = new StringBuffer();
StringBuffer tostring = new StringBuffer("\n public String toString(){\n return \"");
result.append( "public class "+tableConverName+" implements java.io.Serializable{\n\n");
result.append( " private static final long serialVersionUID = 1L;\n");
result.append( " /**表名**/ \n");
result.append( " public static String TABLE = \""+tableConverName+"\";" );
tostring.append(tableConverName+" [");
String sql = "select column_name,data_type from information_schema.columns where table_name = '"+ta<span style="white-space:pre"> </span>bleName+"';";
try {
Statement statement = conn.createStatement();
ResultSet resultSet = statement.executeQuery(sql);
while (resultSet.next()) {
if (resultSet.getString(1)!=null&&!resultSet.getString(1).isEmpty()) {
String datatype = MyStringUtil.DatabasetypeConver(resultSet.getString(2));
if(datatype.equals("Date"))result.insert(0,"import java.util.Date;\n");
String rowname1 = MyStringUtil.StringToCamleCaseClassProte(resultSet.getStr<span style="white-space:pre"> </span>ing(1));
String rowname2 = MyStringUtil.StringToCamleCaseClassName(resultSet.getStri<span style="white-space:pre"> </span>ng(1));
String row = " private "+datatype+" "+rowname1+";";
String getAndSet = " public "+datatype+" get"+rowname2+"(){\n <span style="white-space:pre"> </span>return this."+rowname1+";\n }\n\n"
+" public void set"+rowname2+"<span style="white-space:pre"> </span>("+datatype+" "+rowname1+"){\n this."+rowname1+" = "+rowname1+"; \n }";
String note = " /****property****/";
tostring.append(rowname1+" =\" +"+ rowname1 +"+\n \", ");
result.append("\n"+note + "\n" +row + "\n" + getAndSet);
}
}
resultSet.close();
statement.close();
tostring.append(" toString ]\";\n }");
result.append("\n"+tostring.toString()+"\n");
result.append("\n }");
result.insert(0,"package "+PACKAGENAME+";\n\n");
return result.toString();
} catch (SQLException e) {
e.printStackTrace();
return null;
}
}
<pre name="code" class="java">/**
* 获得连接
* @return
*/
public static Connection getConnection() {
try {
Class.forName(JDBC_DRIVER);
conn = DriverManager.getConnection(URL, USER_NAME, PASSWORD);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return conn;
}
6、贴上porperties读取文件PropertiesReader.java
InputStream inputStream = null;
private Properties properties;
public PropertiesReader(String fileName, String encoding) {
try {
inputStream = Thread.currentThread().getContextClassLoader()
.getResourceAsStream(fileName);
if (inputStream == null)
throw new IllegalArgumentException(
"Properties file not found in classpath: " + fileName);
properties = new Properties();
properties.load(new InputStreamReader(inputStream, encoding));
} catch (IOException e) {
throw new RuntimeException("Error loading properties file.", e);
} finally {
if (inputStream != null)
try {
inputStream.close();
} catch (IOException e) {
System.out.println("流关闭异常!\n" + e.getMessage());
}
}
}
public Properties getProperties() {
return properties;
}
public void setProperties(Properties properties) {
this.properties = properties;
}
7、最后刷新工程,一看,bean包下已经生成了文件。