---
title: "【转】hibernate动态创建表，修改表字段"
author: "wangyanlong0107"
date: "2012-10-22T18:50:53Z"
tags: []
categories: ["企业架构"]
slug: "hibernate"
draft: false
lastmod: "2012-10-22T18:50:53Z"
id: 1703213
url: "https://bigdragon.iteye.com/blog/1703213"
---

我们知道,hibernate的tool工具中有个包hbm2ddl可以通过hibernate的映射文对数据库进行ddl操作，而在配置文件中加 入&lt;property name="hbm2ddl.auto"&gt;update&lt;/property&gt;，就可以根据映射文件进行ddl操作了。

那我们要在运行创建表，或修改表的字段，那我们可以先通过 DOM修改配置文件来间接修改数据库

那要创建数据库表的话，只要创建了新的映射文件，并通过映射文件进行插入操作，就可以创建表了

那我们要修改数据库表的字段怎么办呢？

hibernate3.0中给我们提供了动态组件的功能，这种映射的优点是通过修改映射文件，就可以在部署时检测真实的属性的能力，所以就可以通过DOM在运行时操作映射文件，这样就修改了属性，当查入一条新的数据了，就可以删除或添加新的字段了  
下面贴出我写的一些代码

hibernate的配置文件：  
&lt;session-factory&gt;  
    &lt;property name="myeclipse.connection.profile"&gt;Oracle&lt;/property&gt;  
    &lt;property name="connection.url"&gt;  
        jdbc:oracle:thin:@192.168.1.52:1521:orclp  
    &lt;/property&gt;  
    &lt;property name="connection.username"&gt;transys&lt;/property&gt;  
    &lt;property name="connection.password"&gt;transys&lt;/property&gt;  
    &lt;property name="connection.driver\_class"&gt;  
        oracle.jdbc.driver.OracleDriver  
    &lt;/property&gt;  
    &lt;property name="format\_sql"&gt;true&lt;/property&gt;  
    &lt;property name="dialect"&gt;  
        org.hibernate.dialect.Oracle9Dialect  
    &lt;/property&gt;  
    &lt;property name="current\_session\_context\_class"&gt;thread&lt;/property&gt;

    &lt;property name="show\_sql"&gt;true&lt;/property&gt;  
    &lt;property name="hbm2ddl.auto"&gt;update&lt;/property&gt;  
&lt;/session-factory&gt;

&lt;/hibernate-configuration&gt;

映射文件：  
&lt;class abstract="false" name="com.tough\_tide.evau.edu\_hall.model.EduHallData" entity-name="EDU\_HALL\_DATA\_01" table="EDU\_HALL\_DATA\_01" schema="TRANSYS"&gt;  
        &lt;id name="eduHallDataId" type="java.lang.String"&gt;  
            &lt;column name="EDU\_HALL\_DATA\_ID" length="20" /&gt;  
            &lt;generator class="sequence" &gt;  
                &lt;param name="sequence"&gt;  
                    EDU\_HALL\_DATA\_01\_SEQ  
                &lt;/param&gt;  
            &lt;/generator&gt;  
        &lt;/id&gt;  
        &lt;property name="sysDeptId" type="java.lang.String"&gt;  
            &lt;column name="SYS\_DEPT\_ID" length="20" not-null="true" /&gt;  
        &lt;/property&gt;  
        &lt;property name="sysUserInfoId" type="java.lang.String"&gt;  
            &lt;column name="SYS\_USER\_INFO\_ID" length="20" not-null="true" /&gt;  
        &lt;/property&gt;  
        &lt;dynamic-component insert="true" name="dataProperties" optimistic-lock="true" unique="false" update="true"&gt;        
        &lt;/dynamic-component&gt;  
    &lt;/class&gt;

修改hibernate中实体属性的类：  
public class HibernateEntityManager {  
    private Component entityProperties;  
    //实体类  
    private Class entityClass;  
    //实体名称  
    private String entityName;  
    //动态组件名称  
    private String componentName;  
    //映射文件名  
    private String mappingName;  
    public String getMappingName() {  
        return mappingName;  
    }  
    public void setMappingName(String mappingName) {  
        this.mappingName = mappingName;  
    }  
    public HibernateEntityManager(String entityName,String componentName,String mappingName){  
        this.entityName=entityName;  
        this.componentName=componentName;  
        this.mappingName=mappingName;  
    }  
    public HibernateEntityManager(Class entityClass,String componentName,String mappingName){  
        this.entityClass=entityClass;  
        this.componentName=componentName;  
        this.mappingName=mappingName;  
    }  
    public Component getEntityProperties(){  
        if(this.entityProperties==null){  
            Property property=getPersistentClass().getProperty(componentName);  
            this.entityProperties=(Component)property.getValue();  
        }  
        return this.entityProperties;  
    }  
    /\**  
     * 添加字段  
     * @param name            添加的字段  
     * @param type            字段的类型  
     \*/  
    public void addEntityField(String name,Class type){  
        SimpleValue simpleValue=new SimpleValue();  
        simpleValue.addColumn(new Column(name));  
        simpleValue.setTypeName(type.getName());  
          
        PersistentClass persistentClass=getPersistentClass();  
        simpleValue.setTable(persistentClass.getTable());  
          
        Property property=new Property();  
        property.setName(name);  
        property.setValue(simpleValue);  
        getEntityProperties().addProperty(property);  
          
        updateMapping();  
    }  
    /\**  
     * 添加多个字段  
     * @param list  
     \*/  
    public void addEntityField(List&lt;FieldInfo&gt; list){  
        for (FieldInfo fi:list) {  
            addEntityField(fi);  
        }  
        updateMapping();  
    }  
    private void addEntityField(FieldInfo fi){  
        String fieldName=fi.getFieldName();  
        String fieldType=fi.getFieldType().getName();  
          
        SimpleValue simpleValue = new SimpleValue();  
        simpleValue.addColumn(new Column(fieldName));  
        simpleValue.setTypeName(fieldType);  
          
        PersistentClass persistentClass = getPersistentClass();  
        simpleValue.setTable(persistentClass.getTable());  
        Property property = new Property();  
        property.setName(fieldName);  
        property.setValue(simpleValue);  
        getEntityProperties().addProperty(property);  
    }  
    /\**  
     * 删除字段  
     * @param name            字段名称  
     \*/  
    public void removeEntityField(String name){  
        Iterator&lt;Property&gt; propertyIterator=getEntityProperties().getPropertyIterator();  
          
        while(propertyIterator.hasNext()){  
            Property property=propertyIterator.next();  
            if(property.getName().equals(name)){  
                propertyIterator.remove();  
                updateMapping();  
                return;  
            }  
        }  
    }  
      
    private synchronized void updateMapping(){  
        HibernateMappingManager hmm=new HibernateMappingManager();  
        hmm.updateClassMapping(this);  
    }  
      
    private PersistentClass getPersistentClass(){  
        if(entityClass==null){  
            return HibernateSessionFactory.getClassMapping(entityName);  
        }else{  
            return HibernateSessionFactory.getConfiguration().getClassMapping(entityClass.getName());  
        }      
    }  
      
      
      
    public String getEntityName() {  
        return entityName;  
    }  
    public void setEntityName(String entityName) {  
        this.entityName = entityName;  
    }  
    public void setEntityProperties(Component entityProperties) {  
        this.entityProperties = entityProperties;  
    }  
    public Class getEntityClass() {  
        return entityClass;  
    }  
    public void setEntityClass(Class entityClass) {  
        this.entityClass = entityClass;  
    }      
    public String getComponentName() {  
        return componentName;  
    }  
    public void setComponentName(String componentName) {  
        this.componentName = componentName;  
    }  
}  
通过DOM修改映射文件的类：  
public class HibernateMappingManager {  
    /\**  
     * 更新映射文件  
     * @param mappingName            映射文件名  
     * @param propertiesList        映射文件的数据  
     \*/  
    public void updateClassMapping(String mappingName,List&lt;Map&lt;String,String&gt;&gt; propertiesList){  
        try {  
            String file=EduHallData.class.getResource(mappingName).getPath();  
              
            Document document=XMLUtil.loadDocument(file);  
            NodeList componentTags=document.getElementsByTagName("dynamic-component");  
            Node node=componentTags.item(0);  
            XMLUtil.removeChildren(node);  
              
            for(Map&lt;String,String&gt; map:propertiesList){  
                Element element=creatPropertyElement(document,map);  
                node.appendChild(element);  
            }          
              
            //XMLUtil.saveDocument(document, file);  
            XMLUtil.saveDocument(null, null);  
        } catch (DOMException e) {  
            // TODO Auto-generated catch block  
            e.printStackTrace();  
        } catch (ParserConfigurationException e) {  
            // TODO Auto-generated catch block  
            e.printStackTrace();  
        } catch (SAXException e) {  
            // TODO Auto-generated catch block  
            e.printStackTrace();  
        } catch (IOException e) {  
            // TODO Auto-generated catch block  
            e.printStackTrace();  
        } catch(TransformerException e){  
            e.printStackTrace();  
        }  
    }  
    /\**  
     * 更新映射文件  
     * @param hem                    HibernateEntityMananger实例  
     \*/  
    public void updateClassMapping(HibernateEntityManager hem){  
        try {  
            String file=EduHallData.class.getResource(hem.getMappingName()).getPath();  
            //Configuration con=HibernateSessionFactory.getConfiguration();  
            //con.addResource(file);  
            //PersistentClass pc=HibernateSessionFactory.getClassMapping("EDU\_HALL\_DATA\_01");  
              
            Document document=XMLUtil.loadDocument(file);  
            NodeList componentTags=document.getElementsByTagName("dynamic-component");  
            Node node=componentTags.item(0);  
            XMLUtil.removeChildren(node);  
              
            Iterator propertyIterator=hem.getEntityProperties().getPropertyIterator();  
            while(propertyIterator.hasNext()){  
                Property property=(Property)propertyIterator.next();  
                Element element=creatPropertyElement(document,property);  
                node.appendChild(element);  
            }  
              
            XMLUtil.saveDocument(document, file);  
        } catch (DOMException e) {  
            // TODO Auto-generated catch block  
            e.printStackTrace();  
        } catch (ParserConfigurationException e) {  
            // TODO Auto-generated catch block  
            e.printStackTrace();  
        } catch (SAXException e) {  
            // TODO Auto-generated catch block  
            e.printStackTrace();  
        } catch (IOException e) {  
            // TODO Auto-generated catch block  
            e.printStackTrace();  
        } catch(TransformerException e){  
            e.printStackTrace();  
        }  
    }  
    private Element creatPropertyElement(Document document,Property property){  
        Element element=document.createElement("property");  
        Type type=property.getType();  
          
        element.setAttribute("name", property.getName());  
        element.setAttribute("column", ((Column)property.getColumnIterator().next()).getName());  
        element.setAttribute("type", type.getReturnedClass().getName());  
        element.setAttribute("not-null", String.valueOf(false));  
          
        return element;  
    }  
    private Element creatPropertyElement(Document document,Map&lt;String,String&gt; map){  
        Element element=document.createElement("property");  
          
        element.setAttribute("name", map.get("name"));  
        element.setAttribute("column", map.get("column"));  
        element.setAttribute("type", map.get("type"));  
        element.setAttribute("not-null", String.valueOf(false));  
          
        return element;  
    }  
    /\**  
     * 修改映射文件的实体名和表名  
     * @param mappingName  
     * @param entityName  
     \*/  
    public void updateEntityName(String mappingName,String entityName){  
        String file=EduHallData.class.getResource(mappingName).getPath();  
        try {  
            Document document=XMLUtil.loadDocument(file);  
            NodeList nodeList=document.getElementsByTagName("class");  
            Element element=(Element)nodeList.item(0);  
            element.setAttribute("entity-name",entityName);  
            element.setAttribute("table", entityName);  
            nodeList=document.getElementsByTagName("param");  
            Element elementParam=(Element)nodeList.item(0);  
            XMLUtil.removeChildren(elementParam);  
            Text text=document.createTextNode(entityName+"\_SEQ");  
            elementParam.appendChild(text);      
            XMLUtil.saveDocument(document, file);  
        } catch (ParserConfigurationException e) {  
            // TODO Auto-generated catch block  
            e.printStackTrace();  
        } catch (SAXException e) {  
            // TODO Auto-generated catch block  
            e.printStackTrace();  
        } catch (IOException e) {  
            // TODO Auto-generated catch block  
            e.printStackTrace();  
        } catch (TransformerException e){  
            e.printStackTrace();  
        }  
          
    }  
    /\**  
     * 更新hibernate的配置文件  
     * @param args  
     \*/  
    public void updateHibernateConfig(String configName,String mappingName){  
        String file=Thread.currentThread().getContextClassLoader().getResource(configName).getPath();  
        String resource=EduHallData.class.getResource(mappingName).toString();  
        String classPath=Thread.currentThread().getContextClassLoader().getResource("").toString();  
        resource=resource.substring(classPath.length());  
        try {  
            Document document=XMLUtil.loadDocument(file);  
            NodeList nodeList=document.getElementsByTagName("session-factory");  
            Element element=(Element)nodeList.item(0);  
            Element elementNew=document.createElement("mapping");  
            elementNew.setAttribute("resource",resource);  
            Text text=document.createTextNode("");  
            element.appendChild(text);  
            element.appendChild(elementNew);  
            XMLUtil.saveDocument(document, file);  
            //XMLUtil.saveDocument(null, null);  
        } catch (ParserConfigurationException e) {  
            // TODO Auto-generated catch block  
            e.printStackTrace();  
        } catch (SAXException e) {  
            // TODO Auto-generated catch block  
            e.printStackTrace();  
        } catch (IOException e) {  
            // TODO Auto-generated catch block  
            e.printStackTrace();  
        } catch (TransformerException e){  
            e.printStackTrace();  
        }  
    }  
}

DOM工具类：  
public class XMLUtil {  
    public static void removeChildren(Node node){  
        NodeList childNodes=node.getChildNodes();  
        int length=childNodes.getLength();  
        for(int i=length-1;i&gt;-1;i--){  
            node.removeChild(childNodes.item(i));  
        }  
    }  
      
    public static Document loadDocument(String file)  
        throws ParserConfigurationException,SAXException,IOException{  
        DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();  
        DocumentBuilder builder=factory.newDocumentBuilder();  
        return builder.parse(file);  
    }  
      
    public static void saveDocument(Document dom,String file)  
        throws TransformerConfigurationException,  
                FileNotFoundException,  
                TransformerException,  
                IOException{  
        TransformerFactory tf=TransformerFactory.newInstance();  
        Transformer transformer=tf.newTransformer();  
          
        transformer.setOutputProperty(OutputKeys.DOCTYPE\_PUBLIC,dom.getDoctype().getPublicId());  
        transformer.setOutputProperty(OutputKeys.DOCTYPE\_SYSTEM, dom.getDoctype().getSystemId());  
          
        DOMSource source=new DOMSource(dom);  
        StreamResult result=new StreamResult();  
          
        FileOutputStream outputStream=new FileOutputStream(file);  
        result.setOutputStream(outputStream);  
        transformer.transform(source, result);  
          
        outputStream.flush();  
        outputStream.close();  
    }  
}