由于项目使用ibatis,众所周知的原因,配置文件很是烦琐,尤其是数据库字段通常情况下又不与实体中的变量名相同,所以进行数据操作时就要进行映射。 这东西配置起来还是比较烦,于是写了个工具类来生成一下,留着备用。
例如,数据库的表名及部分字段是这样的
都是大写的且使用下划线分割,然后我是使用myeclipse DB Browser连接数据库并通过hibernate 反向生成实体类,部分如下
public class CnfFeesConfig implements java.io.Serializable {
private static final long serialVersionUID = -5883040369836437293L;
private String sysConfigId;
private String versionId;
private String itemId;
private String itemNameCn;
private String itemNameEn;
//get、set
}
接下来就是转换的工具类了,代码很简单,就是通过类全路径装载类,取得类的信息,比如类名,变量列表等,然后做转换,组装。最后输出在控制台,拷过去小做修改就行。
package test.ibatis;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
/**
* 用于生成ibatis对应的各项语句,输出到控制台
*/
public class GenerateIbatisSql {
/**
* 生成别名及resultMap
* @param getSqlClassName 完整的类名称
* @param extendMap 父map
*/
public static void generateMap(String getSqlClassName, String extendMap)
throws InstantiationException, IllegalAccessException,
ClassNotFoundException {
Class<?> cls = Class.forName(getSqlClassName);
Document document = DocumentHelper.createDocument();
Element rootElement = document.addElement("sqlMap");
String className = cls.getName();
String clsName = cls.getSimpleName();
Element typeElement = rootElement.addElement("typeAlias");
typeElement.addAttribute("alias", clsName + "Class");
typeElement.addAttribute("type", className);
Element subElement = rootElement.addElement("resultMap");
subElement.addAttribute("id", clsName + "Map");
subElement.addAttribute("class", clsName + "Class");
if (null != extendMap)
subElement.addAttribute("extends", extendMap);
Field[] fields = cls.getDeclaredFields();
for (Field field : fields) {
if (!field.getName().equals("serialVersionUID")) {
Element resultElement = subElement.addElement("result");
String name = field.getName();
name = trandslate(name);
resultElement.addAttribute("property", field.getName());
resultElement.addAttribute("column", name);
}
}
System.out.println(document.asXML());
}
/**
* 生成选择语句,只生成了字段
*/
public static void generateSelectSql(String getSqlClassName,
String tableAlias) throws ClassNotFoundException,
InstantiationException, IllegalAccessException {
Class<?> cls = Class.forName(getSqlClassName);
Field[] fields = cls.getDeclaredFields();
for (Field field : fields) {
if (!field.getName().equals("serialVersionUID")) {
String name = field.getName();
name = trandslate(name);
System.out.println(tableAlias + "." + name + ",");
}
}
}
/**
* 生成update语句
*/
public static void generateUpdateSql(String className, String symbol)
throws ClassNotFoundException,
InstantiationException, IllegalAccessException {
Class<?> cls = Class.forName(className);
String clsName = cls.getSimpleName();
StringBuilder build = new StringBuilder();
build.append("<update id=\"update").append(clsName).append("\">\n");
clsName = trandslate(clsName);
build.append("UPDATE ").append(clsName.toUpperCase()).append(" SET \n");
//转换变量名
Field[] fields = cls.getDeclaredFields();
for (Field field : fields) {
if (!field.getName().equals("serialVersionUID")) {
String name = field.getName();
name = trandslate(name);
build.append(name.toUpperCase()).append("=").append(symbol)
.append(field.getName()).append(symbol).append(",");
}
}
String result = build.toString();
result = result.substring(0, result.length()-1);
result += "\n</update>";
System.out.println(result);
}
/**
* 生成insert语句
*/
public static void generateInsertSql(String className, String symbol)
throws ClassNotFoundException, InstantiationException,
IllegalAccessException {
Class<?> cls = Class.forName(className);
String clsName = cls.getSimpleName(); //类名
StringBuilder build = new StringBuilder();
build.append("<insert id=\"insert").append(clsName).append("\">\n");
clsName = trandslate(clsName);
build.append("INSERT INTO ").append(clsName.toUpperCase());
List<String> fieldList = new ArrayList<String>();
List<String> valueList = new ArrayList<String>();
Field[] fields = cls.getDeclaredFields();
for (Field field : fields) {
if (!field.getName().equals("serialVersionUID")) {
String name = field.getName();
name = trandslate(name);
fieldList.add(name);
valueList.add(field.getName());
}
}
build.append(" (\n");
for (int i=0,size=fieldList.size(); i<size; i++) {
build.append( fieldList.get(i).toUpperCase() );
if( i < size-1 )
build.append(",");
}
build.append("\n) values (\n");
for (int i=0,size=valueList.size(); i<size; i++) {
build.append(symbol).append(valueList.get(i)).append(symbol);
if( i < size-1 )
build.append(",");
}
build.append("\n)\n</insert>");
System.out.println(build.toString());
}
/**变量名的转换,转成表的字段名*/
private static String trandslate(String name){
//匹配大写
Pattern pattern = Pattern.compile("[A-Z]");
Matcher matcher = pattern.matcher(name);
while (matcher.find()) {
if (matcher.start() == 0)
name = name.replace(matcher.group(), matcher.group().toLowerCase());
else
name = name.replace(matcher.group(), "_" + matcher.group().toLowerCase());//替换下划线
}
return name;
}
public static void main(String[] args) {
//类的全路径名
String className = "com.cmhit.szps.model.cnf.CnfFeesConfig";
//标识符号
String symbol = "";
try {
generateMap(className, null); //生成别名及resultMap
// symbol = "t";
// generateSelectSql(className, symbol); //生成查询语句
// symbol = "#";
// generateInsertSql(className, symbol); //生成插入语句
// generateUpdateSql(className,symbol); //生成更新语句
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
结果
<?xml version="1.0" encoding="UTF-8"?>
<sqlMap>
<typeAlias alias="CnfFeesConfigClass" type="com.cmhit.szps.model.cnf.CnfFeesConfig"/>
<resultMap id="CnfFeesConfigMap" class="CnfFeesConfigClass">
<result property="sysConfigId" column="sys_config_id"/>
<result property="versionId" column="version_id"/>
<result property="itemId" column="item_id"/>
</resultMap>
</sqlMap>