对比很低Hbm文件和数据库中字段的差别

package com.vtobank.comm.logicflow;


import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;


import com.vtobank.system.context.AppContext;
@Controller
public class TestHbmFieldController {
Logger logger = Logger.getLogger(TestHbmFieldController.class);
// 获取到所有的hbm文件,并写入到文件中
static List list = new ArrayList();


private static Map> hbmMap = new HashMap>();
private static Map> fieldMap = new HashMap>();
private static List  noHbm = new ArrayList<>();
private static List  noField = new ArrayList<>();


static String table_regex = "table=\"([0-9a-zA-Z_]+)\"";


static String field_regex = "column=\"([0-9a-zA-Z_]+)\"";


static Pattern tablePattern = Pattern.compile(table_regex);


static Pattern fieldPattern = Pattern.compile(field_regex);


public static Map> getHbmMap() {
return hbmMap;
}


public static void setHbmMap(Map> hbmMap) {
TestHbmFieldController.hbmMap = hbmMap;
}

@ResponseBody
@RequestMapping("getHbmInfos.h5")
public  String getHbmInfos() throws Exception {
String path = Thread.currentThread().getContextClassLoader().getResource("").getPath().split("WEB-INF")[0];
// 生成存储所有hbm文件路径的TXT文本
getHbmInfos(path);
logger.info("===================================");
// 从数据库中获取所有表的所有字段 放入fieldMap
getTableCoulmnFromDb();
logger.info("=========COMPARE===================");
compare();
//将结果写入文件
noHbm.addAll(noField);
writeToFile(new File(path + "/hbm.txt"),noHbm);
logger.info("=========end===================");
return path +"/hbm.txt";
}

/**
* 进行对比
*/
private void compare() {
for (String table : hbmMap.keySet()) {
if (!fieldMap.containsKey(table)) {
logger.info(" no table = " + table);
noHbm.add("该hbm文件无对应实体表:"+table);
continue;
}
Set dbFields = fieldMap.get(table);
for (String field : hbmMap.get(table)) {
if (!dbFields.contains(field)) {
noField.add("数据库无此字段:表名:"+table+",字段:"+field);
logger.info(table + "," + field);
}
}

Set fileds = hbmMap.get(table);
for (String field : fieldMap.get(table)) {
if (!fileds.contains(field)) {
noField.add("hbm文件无此字段:表名:"+table+",字段:"+field);
logger.debug(table + "," + field);
}
}
}

}


/**
* 将hbm路径写入TXT文件并将对应的字段存入hbmMap中
* @param path
* @throws Exception
*/
private  void getHbmInfos(String path) throws Exception {
logger.info("根路径为:" + path);
File file = new File(path + "/hbm.txt");
if (file.exists()) {
file.delete();
}
if (!file.exists()) {
file.createNewFile();
}
list = getHbmFileNames(path);
writeToFile(file);
logger.info("===================================");
List hbms = FileUtils.readLines(new File(path + "/hbm.txt"));
if (hbms != null && hbms.size() > 0) {
for (String line : hbms) {
if (StringUtils.isBlank(line)) {
continue;
}
File dir = new File(line.trim());
if (dir.exists() && dir.getName().endsWith("hbm.xml")) {
// 获取所有hbm文件的字段 放入 hbmMap
getFieldsFromHbm(dir);
}
}
}
}
/**
* 将hbm文件路径写入文件
* @param file
*/
public  void writeToFile(File file) {
FileWriter fw = null;
BufferedWriter writer = null;
int num = 0;
try {
fw = new FileWriter(file);
writer = new BufferedWriter(fw);
for (String name : list) {
writer.write(name.toString());
logger.debug("写入:" + name.toString());
writer.newLine();// 换行 num++;
}
logger.info("list中的值为:" + list.size());
logger.info("写入了" + num + "条记录");
writer.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
writer.close();
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 将对比结果写入文件
* @param file
* @param context
*/
public  void writeToFile(File file,List context) {
FileWriter fw = null;
BufferedWriter writer = null;
int num = 0;
try {
fw = new FileWriter(file);
writer = new BufferedWriter(fw);
for (String name : context) {
writer.write(name.toString());
logger.info("写入:" + name.toString());
writer.newLine();// 换行 
num++;
}
logger.info("list中的值为:" + list.size());
logger.info("写入了" + num + "条记录");
writer.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
writer.close();
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}


private  void getFieldsFromHbm(File hbmFile) throws Exception {
String tableName = "";
String content = FileUtils.readFileToString(hbmFile, "utf-8");
content = StringUtils.deleteWhitespace(content);
// System.out.println("xml去除空格后内容是:" + content);
Matcher mat = tablePattern.matcher(content);
while (mat.find()) {
logger.debug("匹配的table是:" + mat.group());
tableName = StringUtils.substringBetween(mat.group(), "\"");
logger.debug("匹配的表明是:" + tableName);
}
if (StringUtils.isBlank(tableName)) {
return;
}
Set fields = new HashSet();
if (hbmMap.containsKey(tableName)) {
fields = hbmMap.get(tableName);
}
mat = fieldPattern.matcher(content);
while (mat.find()) {
// logger.debug("匹配的字段是:" + mat.group());
String fieldName = StringUtils.substringBetween(mat.group(), "\"");
// logger.debug("匹配的字段结果是:" + fieldName);
fields.add(fieldName);
}
hbmMap.put(tableName, fields);
}


public  List getHbmFileNames(String strPath) {
File dir = new File(strPath);
File[] files = dir.listFiles(); // 该文件目录下文件全部放入数组
if (files != null) {
for (int i = 0; i < files.length; i++) {
String fileName = files[i].getName();
if (files[i].isDirectory()) { // 判断是文件还是文件夹
getHbmFileNames(files[i].getAbsolutePath()); // 获取文件绝对路径
} else if (fileName.endsWith("hbm.xml")) { // 判断文件名是否以.hbm.xml结尾
String strFileName = files[i].getAbsolutePath();
logger.debug("文件名为:" + files[i].getName());
logger.debug("文件路径为:" + strFileName);
list.add(strFileName);
} else {
continue;
}
}
return list;
}
return null;


}
/**
* 获取数据库中所有表的所有字段 存入fieldMap
* @return
* @throws SQLException
* @throws ClassNotFoundException
*/
public  Map> getTableCoulmnFromDb() throws SQLException, ClassNotFoundException {
// URL指向要访问的数据库名test1
/*String url = "jdbc:mysql://47.93.115.174:3306/tyrcb148";
// MySQL配置时的用户名
String user = "root";
// Java连接MySQL配置时的密码
String password = "yinfeng2012";
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection(url, user, password);*/
Connection conn = AppContext.getLocalDataSource().getConnection();
logger.info("数据库连接正常");
Statement st = conn.createStatement();
String tablesql = "select COLUMN_NAME ,TABLE_NAME from information_schema.COLUMNS where  table_schema = 'tyrcb148'";
ResultSet rs = st.executeQuery(tablesql);


while (rs.next()) {
String tableName = (String) rs.getObject("TABLE_NAME");
if (fieldMap.containsKey(tableName)) {
fieldMap.get(tableName).add(rs.getString("COLUMN_NAME"));
} else {
Set fields = new HashSet();
fields.add(rs.getString("COLUMN_NAME"));
fieldMap.put(tableName, fields);
}
}
logger.info("fieldMap size=" + fieldMap.size());
return fieldMap;


}


}

你可能感兴趣的:(对比很低Hbm文件和数据库中字段的差别)