JFinal 鏈接數據庫生成Model類

很喜歡JFinal 框架的,簡單,不用像SSH那樣亂七八糟的注入,配置。不過用慣了Hibernate,Eclipse 能夠直接鏈接數據庫,批量生成表對象類。嘿嘿……「懶惰」驅使,那就本身寫一個吧,確定之後的學習中,JFinal是頗有用的,就寫了這個CreateJfinalEntityUtil 工具類。用的是POSTGRESQL數據庫,這個數據庫很是不錯,呵呵……寫的很差,你們勿噴。 java

package xidian.wwf.utils;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;


/**
 * 映射數據庫,自動生成Entity
 * @author WWF
 */
public class CreateJfinalEntityUtil {
	
	private static Connection conn = null;
	private static final String URL;
	private static final String JDBC_DRIVER;
	private static final String USER_NAME;
	private static final String PASSWORD;
	private static final String DATABASENAME;
	private static final String PACKAGENAME;
	static {
		DATABASENAME = "數據庫名";
		URL = "jdbc:postgresql://localhost:5432/"+DATABASENAME;
		JDBC_DRIVER = "org.postgresql.Driver";
		USER_NAME = "數據庫賬號";
		PASSWORD = "密碼";
		PACKAGENAME = "xidian.wwf.entity";
	}
	
	/**
	 * 得到鏈接
	 * @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;
	}
	
	/**
	 * 關閉數據庫
	 */
	public static void closeConnection(){
		try {
			if (conn != null && !conn.isClosed()) {
				conn.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 生成字段靜態聲明
	 * @param connection
	 * @param tableName
	 * @return
	 */
	private static String CreateEntityString(String tableName){
		String result  = "package "+PACKAGENAME+";\n\n";
		result += "import com.jfinal.plugin.activerecord.Model; \n\n";
		result += "public class "+StringUtil.toLowerCaseTheFristChar(tableName)+" extends Model<"+StringUtil.toLowerCaseTheFristChar(tableName)+">{\n\n";
		result += "    private static final long serialVersionUID = 1L;\n";
		result += "    public static final "+StringUtil.toLowerCaseTheFristChar(tableName)+" dao = new "+StringUtil.toLowerCaseTheFristChar(tableName)+"();\n\n";
		result += "    /**表名**/ \n" ;
		result += "    public static String TABLE = \""+tableName+"\";" ;
		String sql = "select column_name from information_schema.columns where table_name = '"+tableName+"';";
		try {
			Statement statement = conn.createStatement();
			ResultSet resultSet =  statement.executeQuery(sql);
			while (resultSet.next()) {
				if (resultSet.getString(1)!=null&&!resultSet.getString(1).isEmpty()) {
					String string = resultSet.getString(1);
					String row = "    public static final String "+ string.toUpperCase(Locale.CHINA) +" = \""+string+"\";";
					String note = "    /****/";
					result += "\n"+note + "\n" +row;
				}
			}
			resultSet.close();
			statement.close();
			result+="\n }";
			return result;
		} catch (SQLException e) {
			e.printStackTrace();
			return null;
		}
	}
	
	/**
	 * 得到數據庫的全部表名
	 * @return
	 */
	public static List<String> getAllTables(){
		String sql = "select relname as TABLE_NAME from pg_class c " +
				"where  relkind = 'r' and relname not like 'pg_%' and relname not like 'sql_%' order by relname";
		try {
			List<String> result = new ArrayList<String>();
			Statement statement = conn.createStatement();
			ResultSet resultSet =  statement.executeQuery(sql);
			while (resultSet.next()) {
				if (resultSet.getString(1)!=null&&!resultSet.getString(1).isEmpty()){
					result.add(resultSet.getString(1));
				}
			}
			return result;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	
	
	
	/**
	 * 生成Entity
	 */
	public static void CreateEntity(){
		try {
			getConnection();
			List<String> tables = getAllTables();
			for (int i = 0; i < tables.size(); i++) {
				File createFolder = new File(System.getProperty("user.dir")+"/src/"+PACKAGENAME.replace(".", "/"));
				//路徑不存在,生成文件夾
				if (!createFolder.exists()) {
					createFolder.mkdirs();
				}
				String entityString = CreateEntityString(tables.get(i).trim());
				File entity = new File(createFolder.getAbsolutePath()+"/"+StringUtil.toLowerCaseTheFristChar(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();
		}
	}
	
	
	
	public static void main(String[] args) {
		CreateEntity();
	}

	

}
相關文章
相關標籤/搜索