.
.
..
.
.
.
import java.io.FileWriter;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import com.jfinal.core.JFinal;
import com.jfinal.plugin.activerecord.DbKit;
import com.tools.so;
public class AutoCreatedEntityName {
public AutoCreatedEntityName() {
}
/***
* 生成表实体
*/
@SuppressWarnings("rawtypes")
private String getEntity(String tableName, Map<String,String> property,String packagename) {
String ln = "\r\n";
StringBuffer sb = new StringBuffer();
sb.append(ln+"\t/***\t\r\n\t*表名:"+tableName+"\t\r\n\t*/");
sb.append(ln + "\tpublic static final class " + FileNameManager.CamelCase(tableName.split("_")) + "{" + ln);
sb.append("\t\tpublic static final String " + "tableName" + "=\"" + tableName+ "\";" + ln);
Iterator i=property.entrySet().iterator();
while(i.hasNext()){
Map.Entry e=(Map.Entry)i.next();
sb.append("\t\tpublic static final String "
+ FileNameManager.CamelCase(e.getKey().toString().split("_")) + "=\"" + e.getKey().toString()
+ "\";" + ln);
}
sb.append("\t\tpublic static final String[] all={");
Iterator is=property.entrySet().iterator();
while(is.hasNext()){
Map.Entry e=(Map.Entry)is.next();
sb.append("\r\n\t\t\t");
sb.append(FileNameManager.CamelCase(e.getKey().toString().split("_")));
sb.append(",");
}
sb.deleteCharAt(sb.length()-1);;
sb.append("\r\n\t\t};\r\n");
sb.append("\t\tpublic static final Integer size=" + property.size() + ";"
+ ln);
sb.append("\t}" + ln);
try {
new AutoCreatedModelFile(FileNameManager.CamelCase(tableName.split("_")),property,packagename);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return sb.toString();
}
@SuppressWarnings({ "rawtypes", "unchecked" })
private String CreatedRFile(Map<String,Map<String,String>> map,String packagename)
{
String ln = "\r\n";
StringBuffer sb = new StringBuffer();
sb.append(ln +"package "+packagename+";"+ln+
"/***"+ln+
" * 表文件结构。"+ln+
" * 对应表文件名。"+ln+
" * 在Model中不需要记住对应的表名。"+ln+
" * 只用此文件中对应的名称。"+ln+
" * 同时避免了字段名修改,删除后程序结构破坏。"+ln+
" * @author 石啸天"+ln+
" *"+ln+
" */"+ln+
"public final class R {"+ln
);
Iterator i=map.entrySet().iterator();
while(i.hasNext()){//只遍历一次,速度快
Map.Entry e=(Map.Entry)i.next();
sb.append(getEntity(e.getKey().toString(),(Map<String,String>)e.getValue(),packagename));
}
sb.append(ln + "}");
return sb.toString();
}
/***
* 读取数组中全部的数据表生成对应R文件
* @param tableName 表名数组
*/
public void created(String[] tableName,String packagename) {
DataBeasTypeToJavaType dtj=new DataBeasTypeToJavaType();
so.p("开始生成实体R文件");
Connection conn = null;
PreparedStatement colunmsPs = null;
Map<String,Map<String,String>> all = new HashMap<String,Map<String,String>>();
try {
conn = DbKit.getConfig().getConnection();
for(int i=0;i<tableName.length;i++){
colunmsPs = conn.prepareStatement("desc " + tableName[i]);
//字段列表
Map<String,String> colunms = new HashMap<String,String>();
ResultSet columnsRs = colunmsPs.executeQuery();
// 获取对应表中的字段
while (columnsRs.next()) {
// colunms.add(columnsRs.getString(1));
// so.p("字段 "+columnsRs.getString(1)+" "+columnsRs.getString(2).split(")")[0]);
colunms.put(columnsRs.getString(1),dtj.get(columnsRs.getString(2).split("\\(")[0]));
}
so.p("表为 " + FileNameManager.CamelCase(tableName[i].split("_")));
all.put(tableName[i],colunms);
colunmsPs.close();
}
conn.close();
// so.p(CreatedRFile(all,packagename));
so.p(packagename);
String[] pn=packagename.split("\\.");
// so.p(pn[0]);
StringBuffer file=new StringBuffer();
String dir=JFinal.me().getServletContext().getRealPath("/");
file.append(dir.substring(0, dir.length()-7)+"src");
for(String p:pn)
{
file.append("\\");
file.append(p);
}
so.p(file.toString());
FileWriter fileWriter=new FileWriter(file.toString()+"/"+"R.java");
fileWriter.write(CreatedRFile(all,packagename));
fileWriter.flush();
fileWriter.close();
so.p("生成完成");
// return getEntity(tableName, property);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
// return null;
}
}
}
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Iterator;
import java.util.Map;
import com.jfinal.core.JFinal;
import com.tools.so;
/***
* 自动生成带setter与getter方法的Model
* @author 石啸天
*
*/
public class AutoCreatedModelFile {
public AutoCreatedModelFile(String tableName, Map<String,String> property,String packageName) throws IOException{
//-----------------------拼装文件夹名
String[] pn=packageName.split("\\.");
StringBuffer file=new StringBuffer();
String dir=JFinal.me().getServletContext().getRealPath("/");
file.append(dir.substring(0, dir.length()-7)+"src");
for(String p:pn)
{
file.append("/");
file.append(p);
}
so.p(file.toString());
//-------------------------------------
//---------------------创建文件
String f=createdFile(file.toString()+"/"+tableName+"/",FileNameManager.upFirstName(tableName)+".java");
FileWriter fileWriter=new FileWriter(f);
fileWriter.write(getText(tableName,property,packageName));
fileWriter.flush();
fileWriter.close();
}
/***
* 创建文本内容
* @param tableName
* @param property
* @return
*/
private String getText(String tableName, Map<String,String> property,String packageName){
String classname=FileNameManager.upFirstName(tableName);
//参数对组
String para=entrypara(property);
String ln = "\r\n";
String tab="\t\t";
StringBuffer sb = new StringBuffer();
sb.append(ln +"package "+packageName+"."+tableName+";"+ln+
"import com.jfinal.plugin.activerecord.Model;"+ln+
"import com.jfinal.plugin.activerecord.TableMapping;"+ln+
"import com.jfinal.plugin.activerecord.Db;"+ln+
"import java.util.HashMap;"+ln+
"import java.util.List;"+ln+
"import java.util.Map;"+ln+
inputPackage(property)+
"/***"+ln+
" * 自动生成的Model"+ln+
" * @author 石啸天"+ln+
" *"+ln+
" */"+ln+
"@SuppressWarnings(\"serial\")"+ln+
"public class "+classname+" extends Model<"+classname+">{"+ln
);
//空构造与有参构造
sb.append(classTextStringLine(new String[]{
"//--------------setter和getter---------------",
entryBean(classname,property),
"//-------------------------------------------",
"/***",
"*数据库操作实体",
"*/",
"public static final "+classname+" dao=new "+classname+"();",
"/**",
"* 表名",
"*/",
"public static final String tableName=\""+tableName+"\";",
"/**",
"* 表主键",
"*/",
"public static final String primaryKey=TableMapping.me().getTable(dao.getClass()).getPrimaryKey();",
"/***",
"* 空构造",
"*/",
"public "+classname+"(){}",
"/***",
"* 有参构造",
"*/",
"public "+classname+"(",
para,
"){",
"setData("+ln+tab+entryparas(property)+ln+tab+");",
"}",
"/***",
"*数据批量设置",
"*/",
"public "+classname+" setData(" +ln+
"\t\t"+para +
"){",
setString(property),
"return this;",
"}",
"/***",
"* 按ID逆序查询全部数据",
"* 出现SQL注入漏洞",
"* @param pageNumber 页码",
"* @param pageSize 每页记录数",
"* @return",
"* @throws Exception ",
"*/",
"public Map<String,Object> paginate(int pageNumber, int pageSize,String para,Object value) throws Exception {",
classTextStringLine(new String[]{
tab+"Object[] o=new Object[]{};",
tab+"StringBuffer sb=new StringBuffer();",
tab+"sb.append(\"from \"+tableName);",
tab+"if(value!=null&&value!=null&&value!=\"\")",
tab+"{",
tab+tab+"o= new Object[]{value};",
tab+tab+"sb.append(\" where \"+para+\"=?\");",
tab+"}",
tab+"sb.append(\" order by \"+primaryKey+\" DESC\");",
//----------------------",
//数据封装",
tab+"Long num=Db.queryLong(\"select count(1) \"+sb.toString(),o);",
tab+"List<?> data = paginate(pageNumber, pageSize, \"select *\", sb.toString(),o).getList();",
tab+"Map<String,Object> m=new HashMap<String, Object>();",
tab+tab+"m.put(\"data\", data);",
tab+tab+"m.put(\"num\", num);",
tab+"return m;",
"}"
})
}));
sb.append(ln + "}");
return sb.toString();
}
/***
* 创建文件
* @param path
* @param filename
* @return
* @throws IOException
*/
private String createdFile(String path,String filename) throws IOException
{
//判断文件夹是否存在
File dir=new File(path);
if(!dir.exists())dir.mkdirs();
so.p(dir.getPath());
//判断文件是否存在
File f=new File(dir.getPath()+"/"+filename);
if(!f.exists())
{
f.createNewFile();
}
else
{
f.delete();
f.createNewFile();
}
return f.getPath();
}
/***
* 文本格式化
* @param s
* @return
*/
private String classTextStringLine(String[] s)
{
StringBuffer sb=new StringBuffer();
for(String k:s)
{
sb.append("\t\t" +k+"\r\n");
}
return sb.toString();
}
/***
* 构建类似Bean
* @param classname
* @param property
* @return
*/
@SuppressWarnings("rawtypes")
private String entryBean(String classname,Map<String,String> property)
{
StringBuffer sb=new StringBuffer();
sb.append("\r\n");
/*//构建引用
Iterator i=property.entrySet().iterator();
while(i.hasNext()){//只遍历一次,速度快
Map.Entry e=(Map.Entry)i.next();
sb.append("\t\tpublic "+e.getValue().toString()+" "
+ FileNameManager.CamelCase(e.getKey().toString().split("_"))+";" + "\r\n");
}*/
//构建setter和getter
Iterator k=property.entrySet().iterator();
while(k.hasNext()){//只遍历一次,速度快
Map.Entry e=(Map.Entry)k.next();
String propetyname=FileNameManager.CamelCase(e.getKey().toString().split("_"));
//setter
sb.append("\t\tpublic "+classname+" set"
+ FileNameManager.upFirstNameNoLowerCase(propetyname)
+"("+e.getValue()+" "+propetyname+"){" +"\r\n"+
classTextStringLine(
new String[]{
// tab"\t\t" +"this." +propetyname+"="+propetyname+ ";",
"\t\t" +"set(\""+e.getKey()+"\","+propetyname+");",
"\t\t" +"return this;",
"\t\t" +"}"
}
)
+ "\r\n");
sb.append("\t\tpublic "+e.getValue()+" get"
+ FileNameManager.upFirstNameNoLowerCase(propetyname)
+"(){" +"\r\n"+
classTextStringLine(
new String[]{
"\t\t" +"return get(\""+e.getKey()+"\");",
"\t\t" +"}"
}
)
+ "\r\n");
}
return sb.toString();
}
/***
* 构建传参的字符串
* @param property
* @return
*/
@SuppressWarnings("rawtypes")
private String entrypara(Map<String,String> property)
{
StringBuffer sb=new StringBuffer();
//构建引用
sb.append("\r\n");
Iterator i=property.entrySet().iterator();
while(i.hasNext()){//只遍历一次,速度快
Map.Entry e=(Map.Entry)i.next();
String propetyname=FileNameManager.CamelCase(e.getKey().toString().split("_"));
sb.append("\t\t\t\t"+e.getValue().toString()+" "
+ propetyname+","+"\r\n");
}
return sb.substring(4, sb.lastIndexOf(","));
}
@SuppressWarnings("rawtypes")
private String entryparas(Map<String,String> property)
{
StringBuffer sb=new StringBuffer();
//构建引用
sb.append("\r\n");
Iterator i=property.entrySet().iterator();
while(i.hasNext()){//只遍历一次,速度快
Map.Entry e=(Map.Entry)i.next();
String propetyname=FileNameManager.CamelCase(e.getKey().toString().split("_"));
sb.append("\t\t\t\t"+propetyname+","+"\r\n");
}
return sb.substring(4, sb.lastIndexOf(","));
}
/***
* 批量set
* @param property
* @return
*/
@SuppressWarnings("rawtypes")
private String setString(Map<String,String> property)
{
StringBuffer sb=new StringBuffer();
//构建引用
sb.append("\r\n");
Iterator i=property.entrySet().iterator();
while(i.hasNext()){//只遍历一次,速度快
Map.Entry e=(Map.Entry)i.next();
String propetyname=FileNameManager.CamelCase(e.getKey().toString().split("_"));
sb.append("\t\t\t\tset(\""+e.getKey().toString()+"\","+ propetyname+");\r\n");
}
return sb.substring(4, sb.length()-2);
}
@SuppressWarnings("rawtypes")
private String inputPackage(Map<String,String> property)
{
StringBuffer sb=new StringBuffer();
//构建引用
sb.append("\r\n");
Iterator i=property.entrySet().iterator();
while(i.hasNext()){//只遍历一次,速度快
Map.Entry e=(Map.Entry)i.next();
String type=e.getValue().toString();
String packages=null;
if(type.equals("BigInteger")){packages="import java.math.BigIntege;\r\nr";}
else if(type.equals("BigDecimal")){packages="import java.math.BigDecimal;\r\n";}
else if(type.equals("Date")){packages="import java.util.Date;\r\n";}
else if(type.equals("Timestamp")){packages="import java.sql.Timestamp;\r\n";}
else if(type.equals("Time")){packages="import java.sql.Time;\r\n";}
else{ packages="";}
sb.append(packages);
}
return sb.toString();
}
}
修改这个文件可以兼容其他数据库
public class DataBeasTypeToJavaType {
public String get(String type)
{
if(type.equals("char")){return "String";}
else if(type.equals("varchar")){return "String";}
else if(type.equals("blob")){return "Byte[]";}
else if(type.equals("text")){return "String";}
else if(type.equals("int")){return "Integer";}
else if(type.equals("tinyint")){return "Integer";}
else if(type.equals("smallint")){return "Integer";}
else if(type.equals("mediumint")){return "Integer";}
else if(type.equals("bit")){return "Boolean";}
else if(type.equals("bigint")){return "BigInteger";}
else if(type.equals("decimal")){return "BigDecimal";}
else if(type.equals("date")){return "Date";}
else if(type.equals("datetime")){return "Timestamp";}
else if(type.equals("timestamp")){return "Timestamp";}
else if(type.equals("time")){return "Time";}
else if(type.equals("year")){return "Date";}
else if(type.equals("float")){return "Float";}
else if(type.equals("double")){return "Double";}
else if(type.equals("integer")){return "Long";}
else{return null;}
}
}
public class FileNameManager {
/***
*
* 首字母大写处理
* 注意:先所有字符小写化
*
*/
public static String upFirstName(String name)
{
String s=null;
if(name!=null)
{
s=name.toLowerCase();
String first=""+s.charAt(0);
first=first.toUpperCase();
s=first+s.substring(1, s.length());
}
return s;
}
/***
*
* 首字母大写处理
*
*/
public static String upFirstNameNoLowerCase(String name)
{
String s=null;
if(name!=null)
{
s=name;
String first=""+s.charAt(0);
first=first.toUpperCase();
s=first+s.substring(1, s.length());
}
return s;
}
/***
*
* 字符数组驼峰命名法处理
*
*/
public static String CamelCase(String n[])
{
String s=null;
if(n!=null&&n.length>0)
{
StringBuffer b=new StringBuffer();
b.append(n[0].toLowerCase());
for(int i=1;i<n.length;i++)
{
b.append(upFirstName(n[i]));
}
s=b.toString();
}
return s;
}
/***
*
* 字符数组首字母大写处理
*
*/
public static String upFirstName(String n[])
{
String s=null;
if(n!=null&&n.length>0)
{
StringBuffer b=new StringBuffer();
for(int i=0;i<n.length;i++)
{
b.append(upFirstName(n[i]));
}
s=b.toString();
}
return s;
}
}
修复了工具包内没有so文件的Bug,下载包点击这里!!