在处理项目过程中,要针对每个table生成一个校验表单,放到程序中的位置;并将此文件加入配置文件中;
如果此文件是第二次生成,只将第一个group节点下的内容替换,第二个group节点不动。
自己就大概的写了一下,感觉有些地方或细节如果处理不够好,请大神们指点下。
1、配置数据库连接
public static Connection getConn(String dataSourceId) throws Exception {
Class.forName("com.mysql.jdbc.Driver") ;
String url = "jdbc:mysql://127.0.0.1:3306/"+dataSourceId+"?characterEncoding=UTF-8" ;
String username = "root" ;
String password = "111222333!" ;
return DriverManager.getConnection(url , username , password) ;
}
2、一个方法,这个是从网上找的 将数据库中的字段如:t_order_amount 转化成 tOrderAmount这种格式。
/**
* 替换字符串并让它的下一个字母为大写
* @param srcStr
* @param org
* @param ob
* @return
*/
public static String replaceUnderlineAndfirstToUpper(String srcStr,String org,String ob)
{
String newString = "";
int first=0;
while(srcStr.indexOf(org)!=-1)
{
first=srcStr.indexOf(org);
if(first!=srcStr.length())
{
newString=newString+srcStr.substring(0,first)+ob;
srcStr=srcStr.substring(first+org.length(),srcStr.length());
srcStr=firstCharacterToUpper(srcStr);
}
}
newString=newString+srcStr;
return newString;
}
/**
* 首字母大写
*
* @param srcStr
* @return
*/
public static String firstCharacterToUpper(String srcStr) {
return srcStr.substring(0, 1).toUpperCase() + srcStr.substring(1);
}
3、===
public static void generatorValidation(String dataSourceId ,String ...tableNames ){
for(String tableName : tableNames){
generatorValidation( dataSourceId , tableName );
}
}
public static void generatorValidation(String dataSourceId ,String tableName ){
boolean flag = true;
tableName = tableName.toLowerCase();
Map map = null;
ArrayList<Map> list = new ArrayList<Map>();
try{
//取得数据库连接
String querySql = " SELECT lower(COLUMN_NAME) as 'col',COLUMN_COMMENT as colName,DATA_TYPE as 'colType' ,CHARACTER_MAXIMUM_LENGTH as 'colLength' FROM information_schema.`COLUMNS` where TABLE_NAME =UPPER('"+tableName+"')";//从系统表中找到表的字段名称,字段注释,字段类型和长度
Connection conn = getConn(dataSourceId);
ResultSet rs = conn.createStatement().executeQuery(querySql.toString());
while(rs.next()){
String col = rs.getString("col");
String colName = rs.getString("colName");
String colType = rs.getString("colType");
String colLength = rs.getString("colLength");
if(StringUtil.isEmptyString(col)){
col="";
}
if(StringUtil.isEmptyString(colName)){
colName= col;
}
if(StringUtil.isEmptyString(colType)){
colType="";
}
if(StringUtil.isEmptyString(colLength)){
colLength="";
}
map = new HashMap();
if(flag){
map.put("col", replaceUnderlineAndfirstToUpper(col,"_",""));
}else{
map.put("col", col);
}
map.put("colName", colName);
map.put("colType", colType);
map.put("colLength", colLength);
list.add(map);
}
//判断文件是否存在
String path = System.getProperty("user.dir") ;
String filePath = path+"/conf/validation/"+tableName+".xml";
File file = new File(filePath);
if(!file.exists()){
//写文件
BuildXMLDoc(tableName,list);
//validation-rules.xml 增加引用
addXmlInclud(tableName);
}else{
updateXMLDoc(tableName,list);
}
rs.close();
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
3、写xml
/***
* 公共的一些校验
*/
private static String[] rule = new String[]{"required","length" };
/**
* 生成XML文件,
* @param tableName
* @param list
* @throws Exception
*/
public static void BuildXMLDoc(String tableName,ArrayList<Map> list) throws Exception {
String path = System.getProperty("user.dir") ;
String filePath = path+"/conf/validation/"+tableName+".xml";//这个路径可以写成动态的
// 创建根节点 并设置它的属性 ;
Element root = DocumentHelper.createElement("validation");
Element grop = root.addElement("group").addAttribute("name",tableName+".validate");
//生成grop 节点 name = tableName+"validate"
Map map = null;
// 将根节点添加到文档中;
Document document = DocumentHelper.createDocument(root);
for(int m = 0 ; m <list.size();m++){
map = new HashMap();
map = list.get(m);
Element elements = grop.addElement("field");
elements.addAttribute("name",map.get("col").toString());
elements.addAttribute("label",map.get("colName").toString());
//设置规则 公共部分
for(int n = 0; n<rule.length;n++){
Element ce = null;
if(rule[n].equals("length")){
if(!StringUtil.isEmptyString(map.get("colLength").toString())){
ce = elements.addElement("rule");
ce.addAttribute("name",rule[n]);
ce.addAttribute("max",map.get("colLength").toString());
}
}else{
ce = elements.addElement("rule");
ce.addAttribute("name",rule[n]);
}
}
//根据字段类型设置,时间设置时间
if("datetime".equals(map.get("colType").toString())){
Element ce = elements.addElement("rule");
ce.addAttribute("name","date");
}
if("int".equals(map.get("colType").toString())){
Element ce = elements.addElement("rule");
ce.addAttribute("name","number");
}
}
OutputFormat format = new OutputFormat(" ",true);
format.setEncoding("utf-8");//设置编码格式
XMLWriter XMLOut = new XMLWriter (new FileOutputStream(filePath),format);
System.out.println(filePath);
XMLOut.write(document );
XMLOut.close();
}
4、将文件引入配置文件
public static final String RULESXML = "aaa.xml";//引入到的配置文件名称
/**
* 将生成的校验文件引入validation-rules.xml
* @param tableName
* @throws Exception
*/
private static void addXmlInclud(String tableName) throws Exception {
Element rootElement = null;
String filePath = System.getProperty("user.dir")+"/conf/"+ RULESXML ;
File file = new File(filePath);
try {
SAXReader builder = new SAXReader();
Document doc = builder.read(file);
rootElement = doc.getRootElement();
Element el = rootElement.addElement("include");
el.addAttribute("file","validation/"+tableName+".xml");
XMLWriter out = new XMLWriter(new FileOutputStream(filePath));
out.write(doc );
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
5、如果校验文件已经存在,只更新第一个节点。
/**
* 已存在的文件重新生成跑规则
* @param tableName
* @param list
* @throws Exception
*/
private static void updateXMLDoc(String tableName, ArrayList<Map> list)throws Exception {
Element rootElement = null;
Map map = null;
String filePath = System.getProperty("user.dir")+"/conf/validation/"+tableName+".xml";
File file = new File(filePath);
try {
SAXReader builder = new SAXReader();
Document doc = builder.read(file);
rootElement = doc.getRootElement();
ArrayList<Element> els = (ArrayList<Element>) rootElement.elements() ;
Element grop = DocumentHelper.createElement("group").addAttribute("name",tableName+".validate");
for(int m = 0 ; m <list.size();m++){
map = new HashMap();
map = list.get(m);
Element elements = grop.addElement("field");
elements.addAttribute("name",map.get("col").toString());
elements.addAttribute("label",map.get("colName").toString());
//设置规则 公共部分
for(int n = 0; n<rule.length;n++){
Element ce = null;
if(rule[n].equals("length")){
if(!StringUtil.isEmptyString(map.get("colLength").toString())){
ce = elements.addElement("rule");
ce.addAttribute("name",rule[n]);
ce.addAttribute("max",map.get("colLength").toString());
}
}else{
ce = elements.addElement("rule");
ce.addAttribute("name",rule[n]);
}
}
//根据字段类型设置,时间设置时间
if("datetime".equals(map.get("colType").toString())){
Element ce = elements.addElement("rule");
ce.addAttribute("name","date");
}
if("int".equals(map.get("colType").toString())){
Element ce = elements.addElement("rule");
ce.addAttribute("name","number");
}
}
//将list的第一个elemnts替换掉
els.set(0, grop);
OutputFormat format = new OutputFormat(" ",true);
XMLWriter out = new XMLWriter(new FileOutputStream(filePath),format);
out.write(doc );
out.close();
//System.out.println(doc.asXML());
} catch (Exception e) {
e.printStackTrace();
}
}