/**
* 根据实体类生成映射文件
*
* @author dxm
*
*/
public class ObjectToMapping {
@SuppressWarnings({ "rawtypes", "resource" })
public static boolean convert(Class cls, File file, String id, boolean identity) throws IOException {
if (null == cls || file == null) {
return false;
}
if (file.isDirectory()) {
file = new File(file.getAbsolutePath() + "//" + cls.getSimpleName() + ".hbm.xml");
}
if (file.exists()) {
file.delete();
}
// 输出流
FileOutputStream fs = new FileOutputStream(file);
// 写头
fs.write("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n".getBytes("UTF-8"));
fs.write("n".getBytes("UTF-8"));
fs.write("\"-//Hibernate/Hibernate Mapping DTD 3.0//EN\"\n".getBytes("UTF-8"));
fs.write("\"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd\">\n".getBytes("UTF-8"));
// 正文
StringBuffer str = new StringBuffer();
str.append("\n");
str.append("\t\n\n");
str.append("\t\t\n\n");
Field[] fls = cls.getDeclaredFields();
Field[] sfls = cls.getSuperclass().getDeclaredFields();
// 只加载父类的主键
for (Field f : sfls) {
if (Modifier.isStatic(f.getModifiers()) || Modifier.isFinal(f.getModifiers())) {
continue;
}
if (f.getName().equals(id)) {
str.append("\t\t\n");
str.append("\t\t\t\n");
if (identity) {
str.append("\t\t\t\n");
}
str.append("\t\t\n\n");
break;
}
}
// 加载当前类的所有属性
for (Field f : fls) {
if (Modifier.isStatic(f.getModifiers()) || Modifier.isFinal(f.getModifiers())) {
continue;
}
if (f.getName().equals(id)) {
str.append("\t\t\n");
str.append("\t\t\t\n");
if (identity) {
str.append("\t\t\t\n");
}
str.append("\t\t\n\n");
continue;
}
str.append("\t\t\n");
str.append("\t\t\t\n");
str.append("\t\t\n\n");
}
// 只加载父类的普通属性
for (Field f : sfls) {
if (Modifier.isStatic(f.getModifiers()) || Modifier.isFinal(f.getModifiers())) {
continue;
}
if (f.getName().equals(id)) {
continue;
}
str.append("\t\t\n");
str.append("\t\t\t\n");
str.append("\t\t\n\n");
}
str.append("\t\n");
str.append("");
fs.write(str.toString().getBytes("UTF-8"));
return false;
}
public static void main(String[] args) throws IOException {
ObjectToMapping.convert(About.class, new File("*"), "timeKey", true);
}
}