hibernate手动创建xx.hbm.xml文件

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.lang.reflect.Field;
/**
 * myeclipse出了问题,没法通过逆向工程生成配置文件,闲来无事自己写个以后可以拿来用,另外,权当练手
 * 
 * @author LOOK
 * 
 */
public class CreateHbmXml {
    /**
     * 输入类的包名及类名,在其目录下创建xxx.hbm.xml文件
     * 
     * @param packageName
     *            类的包名
     * @param className
     *            类名
     */
    public static void createHbmXML(String packageName, String className) {
        try {
            Class clazz = Class.forName(packageName + "." + className);
            Field[] fields = clazz.getDeclaredFields();
            StringBuilder sBuilder = new StringBuilder();
            sBuilder.append("\n"
                    + " \n");
            sBuilder.append("\n");
            sBuilder.append("\n");
            for (Field field : fields) {
                String param = field.getName();
                if ("id".equals(param)) {
                    sBuilder.append("\t\n");
                } else {
                    sBuilder.append("\t\n");
                }
            }
            sBuilder.append(" \n");
            File directory = new File(".");
            String path = directory.getCanonicalPath();
            packageName = packageName.replace('.', File.separatorChar);
            String fileName = className + ".hbm.xml";
            path = path + File.separator + "src" + File.separator + packageName
                    + File.separator + fileName;
            createFile(sBuilder, className, path);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 首字母小写。ClientInfo-->clientInfo
     * 
     * @param className
     *            类名
     * @return 属性名
     */
    public static String firstToLowCase(String className) {
        char temp[] = className.toCharArray();
        temp[0] += 32;
        String string = String.valueOf(temp);
        return string;
    }

    /**
     * 创建xx.hbm.xml文件
     * 
     * @param sBuilder
     * @param className
     */
    public static void createFile(StringBuilder sBuilder, String className,
            String path) {
        File file = new File(path);
        try {
            if (file.exists()) {
                file.delete();
                file.createNewFile();
                System.out.println("文件重新创建");
            }
            Writer out = new FileWriter(file);
            out.write(sBuilder.toString());
            out.close();
            System.out.println("创建成功");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

你可能感兴趣的:(hibernate手动创建xx.hbm.xml文件)