`
zhaoyanfangeye
  • 浏览: 122989 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

w3c 中doc生成一个基于hibernate的hbm.xml文件

阅读更多
package com.gosophia.metadataEngine.commons;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.Iterator;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.hibernate.Session;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.cfg.Configuration;
import org.w3c.dom.DOMImplementation;
import org.w3c.dom.Document;
import org.w3c.dom.DocumentType;
import org.w3c.dom.Element;
import org.w3c.dom.Text;

import com.gosophia.metadataEngine.entity.MetadataField;
import com.gosophia.metadataEngine.entity.MetadataTable;

/**
 * 
 * 将一个Table信息转化为一个xml文件
 * 
 * @创建日期 2010-5-28
 * 
 * @版本 V1.0
 */
public class MatadataTableToXML {
    public final static String PUBLIC = "-//Hibernate/Hibernate Mapping DTD 3.0//EN";// 头部信息
    public final static String SYSTEM = "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd";// 头部信息dtd
    public final static String PATH = "src/main/resources/hbmXml/";// 创建文件输出的路径
    public final static String FILETYPE = ".hbm.xml";// 创建出文件的类型;
//    DocumentType d
    /**
     * 
     * @param tableId
     *            表的编号
     */
    public static void createXml(long tableId, Session session) {
        // 创建一个解析器工厂
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder documentBuilder = null;
        
        try {
            documentBuilder = factory.newDocumentBuilder();
            Document document =documentBuilder.newDocument();
            // 创建一个根节点
            Element root = document.createElement("hibernate-mapping");
            document.appendChild(root);
            // 创建一个类节点
            Element classNode = document.createElement("class");
            // 获得当前系统表
            MetadataTable metadata = (MetadataTable) session.get(
                    MetadataTable.class, tableId);
            if(metadata==null){
                throw new RuntimeException("元数据表为空!");
            }
            // 添加属性--value是动态的------
            classNode
                    .setAttribute("entity-name", metadata.getEntityClassName());
            classNode.setAttribute("table",metadata.getTableName());
            root.appendChild(classNode);

            // 获得当前表所对应的字段
            List<MetadataField> fields = metadata.getColTabMetadataFields();
            Iterator<MetadataField> iterField = fields.iterator();
            while (iterField.hasNext()) {
                MetadataField metadataField = iterField.next();
                // 判断是否是主键
                if (metadataField.getEntityPropertyName() != null
                        && metadataField.getEntityPropertyName().trim()
                                .toLowerCase().equals("id")) {
                    Element id = document.createElement("id");
                    id.setAttribute("name", metadataField
                            .getEntityPropertyName());
                    id.setAttribute("type", metadataField
                            .getEntityPropertyType());
                    id.setAttribute("column", metadataField.getFieldName());
                    // 主键生成策略
                    Element generator = document.createElement("generator");
                    generator.setAttribute("class", "sequence");
                    id.appendChild(generator);
                    classNode.appendChild(id);
                } else {
                    Element property = document.createElement("property");
                    property.setAttribute("name", metadataField
                            .getEntityPropertyName());
                    property.setAttribute("column", metadataField
                            .getFieldName());
                    property.setAttribute("type", metadataField
                            .getEntityPropertyType());
                    classNode.appendChild(property);
                }
            }
            // 创建一个转换器工厂
            TransformerFactory transFactroy = TransformerFactory.newInstance();
            Transformer transforer = transFactroy.newTransformer();
            transforer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, SYSTEM);
            transforer.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, PUBLIC);
            // 将文档对象封装在DOMSource中
            DOMSource domsource = new DOMSource(document);
            // 定义一个xml文件输出目录
            File file = new File(PATH + metadata.getEntityClassName()
                    + FILETYPE);
            FileOutputStream fileOutPut = new FileOutputStream(file);

            StreamResult xmlResult = new StreamResult(fileOutPut);
            transforer.transform(domsource, xmlResult);
            
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (TransformerConfigurationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ParserConfigurationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (TransformerException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
/*******
* Configuration动态读取生成出来的hbm文件
*/
//文件生成出的路径
    public static String LOCATION = SessionUtil.class.getProtectionDomain()
            .getCodeSource().getLocation().getFile()
            + "/../";
    /**
     * 重新扫描hbm配置文件(xml)
     */
    public synchronized static void reloadConfiguration() {
        if (sessionFactory != null && !sessionFactory.isClosed()) {
            sessionFactory.close();
            sessionFactory = null;
        }

        Configuration config = new AnnotationConfiguration().configure();

        File file = new File(SessionUtil.LOCATION + "hbmXml/");

        if (!file.exists()) {
            sessionFactory = null;
        } else {
            // 解析动态生成的hbm文件
            config.addDirectory(file);
            sessionFactory = config.buildSessionFactory();
        }
    }

======================================================================
       /**
     * 
     * @param tableId
     *            表的编号
     * 已String字符串的方式保存xml
     */
    public static String createXmlString(long tableId, Session session) {
        // 创建一个解析器工厂
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder documentBuilder = null;
        ByteArrayOutputStream  outputStream=new  ByteArrayOutputStream();
        try {
            documentBuilder = factory.newDocumentBuilder();
            Document document = documentBuilder.newDocument();
            // 创建一个根节点
            Element root = document.createElement("hibernate-mapping");
            document.appendChild(root);
            // 创建一个类节点
            Element classNode = document.createElement("class");
            // 获得当前系统表
            MetadataTable metadata = (MetadataTable) session.get(
                    MetadataTable.class, tableId);
            if (metadata == null) {
                throw new RuntimeException("元数据表为空!");
            }
            // 添加属性--value是动态的------
            classNode
                    .setAttribute("entity-name", metadata.getEntityClassName());
            classNode.setAttribute("table", metadata.getTableName()
                    .toLowerCase());
            root.appendChild(classNode);

            // 获得当前表所对应的字段
            List<MetadataField> fields = metadata.getColTabMetadataFields();
            Iterator<MetadataField> iterField = fields.iterator();
            while (iterField.hasNext()) {
                MetadataField metadataField = iterField.next();
                // 判断是否是主键
                if (metadataField.getEntityPropertyName() != null
                        && metadataField.getEntityPropertyName().trim()
                                .toLowerCase().equals("id")) {
                    Element id = document.createElement("id");
                    id.setAttribute("name", metadataField
                            .getEntityPropertyName());
                    id.setAttribute("type", metadataField
                            .getEntityPropertyType());
                    id.setAttribute("column", metadataField.getFieldName());
                    // 主键生成策略
                    Element generator = document.createElement("generator");
                    generator.setAttribute("class", "sequence");
                    id.appendChild(generator);
                    classNode.appendChild(id);
                } else {
                    Element property = document.createElement("property");
                    property.setAttribute("name", metadataField
                            .getEntityPropertyName());
                    property.setAttribute("column", metadataField
                            .getFieldName());
                    property.setAttribute("type", metadataField
                            .getEntityPropertyType());
                    classNode.appendChild(property);
                }
            }
            // 创建一个转换器工厂
            TransformerFactory transFactroy = TransformerFactory.newInstance();
            Transformer transforer = transFactroy.newTransformer();
            transforer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, SYSTEM);
            transforer.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, PUBLIC);
            // 将文档对象封装在DOMSource中
            DOMSource domsource = new DOMSource(document);
            outputStream  =  new  ByteArrayOutputStream(); 
            StreamResult xmlResult = new StreamResult(outputStream);
            transforer.transform(domsource, xmlResult);
        } catch (TransformerConfigurationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ParserConfigurationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (TransformerException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally{
            
            try {
                outputStream.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return outputStream.toString();
    }
}
/***
*读取String方式的hbm文件
*
/
    /**
     * 重新扫描hbm配置文件
     */
    public synchronized static void reloadConfiguration(List<String> strXml) {
        if (sessionFactory != null && !sessionFactory.isClosed()) {
            sessionFactory.close();
            sessionFactory = null;
        }

        Configuration config = new AnnotationConfiguration().configure();
        List<String> newXml = strXml;
        for (String xml : newXml) {
            // 解析动态生成的hbm文件
            config.addXML(xml);
        }
        sessionFactory = config.buildSessionFactory();

    }
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics