`
wangyanlong0107
  • 浏览: 495077 次
  • 性别: Icon_minigender_1
  • 来自: 沈阳
社区版块
存档分类
最新评论

【转】hibernate动态创建表,修改表字段

 
阅读更多

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

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

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

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

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


hibernate的配置文件:
<session-factory>
    <property name="myeclipse.connection.profile">Oracle</property>
    <property name="connection.url">
        jdbc:oracle:thin:@192.168.1.52:1521:orclp
    </property>
    <property name="connection.username">transys</property>
    <property name="connection.password">transys</property>
    <property name="connection.driver_class">
        oracle.jdbc.driver.OracleDriver
    </property>
    <property name="format_sql">true</property>
    <property name="dialect">
        org.hibernate.dialect.Oracle9Dialect
    </property>
    <property name="current_session_context_class">thread</property>

    <property name="show_sql">true</property>
    <property name="hbm2ddl.auto">update</property>
</session-factory>

</hibernate-configuration>

映射文件:
<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">
        <id name="eduHallDataId" type="java.lang.String">
            <column name="EDU_HALL_DATA_ID" length="20" />
            <generator class="sequence" >
                <param name="sequence">
                    EDU_HALL_DATA_01_SEQ
                </param>
            </generator>
        </id>
        <property name="sysDeptId" type="java.lang.String">
            <column name="SYS_DEPT_ID" length="20" not-null="true" />
        </property>
        <property name="sysUserInfoId" type="java.lang.String">
            <column name="SYS_USER_INFO_ID" length="20" not-null="true" />
        </property>
        <dynamic-component insert="true" name="dataProperties" optimistic-lock="true" unique="false" update="true">      
        </dynamic-component>
    </class>

修改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<FieldInfo> 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<Property> 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<Map<String,String>> 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<String,String> 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<String,String> 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>-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();
    }
}

分享到:
评论

相关推荐

    Spring Data JPA/Hibernate 运行期动态模型、动态实体建表、动态字段查询的方式

    涉及到动态生成表结构,动态生成模型实体类动态查询表字段等等,经过调研发现hibernate在这方面是很方便的,调用内置API就能完成系列操作,下面贴出核心代码: /** * @author cjbi */ public class DynamicDdlTest...

    使用hibernate封装方法

    - 实体类(Entity)对应数据库中的表,通过注解(@Entity, @Table, @Column等)声明其属性与表字段的映射。 4. **实体关联**: - 如果涉及到两个表的操作,例如用户(User)和角色(Role),可以通过@ManyToOne, ...

    Hibernate 经典总结

    例如,如果要使用 Hibernate 创建一张名为 t_user 的表,包含主键 id、name、age 和 pwd 四个字段,我们需要创建一个对应 Pojo 类(如 User),并确保其属性与表字段一一对应,然后使用 Hibernate API 进行实例化、...

    hibernate xml

    5. **XML配置动态加载**:在程序运行时,Hibernate会读取这些XML文件,根据其内容创建对象并进行相应的数据库操作。这使得配置具有一定的灵活性,可以通过更改XML文件而无需修改代码来调整应用程序的行为。 6. **...

    Hibernate 用法实例

    2. **注解映射**: 使用Java注解在实体类上直接声明属性与表字段的映射。 ### 五、对象的持久化 1. **保存(Save)**: 将瞬时状态的对象转换为持久化状态。 2. **更新(Update)**: 修改持久化对象的属性,并更新到...

    Hibernate课程的总结

    2. 属性映射:通过`@Id`指定主键,`@GeneratedValue`管理自增策略,其他属性对应表字段,如`@Column`。 3. 关系映射:处理一对一、一对多、多对多关系,如`@OneToOne`、`@OneToMany`、`@ManyToOne`和`@ManyToMany`。...

    Eclipse Hibernate基本配置及简单实现

    1. **创建Java类**: 为要持久化的数据表创建对应的Java类,比如User类,包含与数据库表字段一一对应的属性。 ```java @Entity @Table(name = "users") public class User { @Id @GeneratedValue(strategy = ...

    hibernate开发文档

    2. **属性映射**:通过注解或XML文件将实体类的属性与数据库表字段对应起来。 3. **主键生成策略**:配置实体类主键的生成方式,如`@GeneratedValue`,可选择自增、UUID、序列等策略。 ### 四、Session API 1. **...

    hibernate大纲

    2. **属性映射**:实体类中的字段通过 `@Column` 等注解与数据库表字段对应。 3. **主键映射**:使用 `@Id` 和 `@GeneratedValue` 注解定义主键生成策略。 4. **关联映射**:`@OneToOne`, `@OneToMany`, `@ManyToOne...

    Hibernate参考手册

    5. 动态模型:允许在运行时动态创建和修改实体类。 八、性能优化 - 使用批处理:批量插入和更新可以显著提升性能。 - 合理设置缓存策略:根据应用需求调整缓存大小和过期时间。 - 分离读写操作:读多写少的场景下,...

    hibernate+gwt2.4

    3. **实体类(Entity)**:代表数据库表,使用`@Entity`注解标识,属性对应表字段,`@Id`注解标识主键。 4. **Session接口**:持久化操作的主要接口,负责对象的创建、读取、更新和删除(CRUD)。 5. **Criteria查询...

    hibernate对象关系映射案例demo

    实体类的属性与数据库表字段对应,使用`@Id`定义主键,`@GeneratedValue`自动生成主键,`@Column`指定列名。例如: ```java @Entity @Table(name = "User") public class User { @Id @GeneratedValue(strategy = ...

    自学hibernate的jar包

    3. **实体类(Entities)**:实体类对应于数据库中的表,它们通过注解(如@Entity)声明,并通过属性与表字段对应。 4. **持久化层接口(SessionFactory & Session)**:SessionFactory是线程安全的,用于创建...

    struts2+hibernate 增删改查

    - **实体类(Entity)**:代表数据库表,通过注解或XML配置与数据库表字段对应。 - **Session接口**:是与数据库交互的主要接口,负责保存、更新、删除和查询数据。 - **Criteria查询**:提供一种面向对象的方式...

    first_demo.rar_DEMO_struts2_struts2 hibernate_简历

    此外,Hibernate的实体类(Entity)会对应数据库中的表,属性映射到表字段,使得数据的持久化变得更加简单。 在实际的开发流程中,简历的创建可能涉及用户填写个人信息、教育背景、工作经验等内容,这些信息会被...

    hibernate参考手册

    4. **动态模型**:探索如何在运行时动态创建和修改持久化模型,以适应不确定的业务需求。 5. **Tuplizers**:介绍Tuplizer接口的作用,用于自定义结果集转换规则。 七、基本的ORM映射 1. **映射声明**:详述.hbm....

    hibernate 帮助文档

    - **属性映射**:定义类属性与表字段的对应关系。 **1.2.2 单向Set-based的关联** - **一对多映射**:例如`Person`与`Address`之间的关系。 - **集合映射**:使用`&lt;set&gt;`元素来映射一个集合类型的属性。 **1.2.3 ...

    Hibernate-Spring-Struts面试题目

    7. 减少表字段数量,增加表关联,利用二级缓存提高性能。 【Struts 框架知识点】 Struts 是基于MVC设计模式的Web应用程序框架。其工作机制如下: 1. Web应用启动时加载ActionServlet,读取struts-config.xml配置。...

    java动态生成表的增删改查

    创建与数据库表对应的Java实体类,比如`User.java`,包含数据库表字段对应的属性和getter/setter方法。 3. **数据访问对象(DAO)**: 创建DAO接口,如`UserDao.java`,定义CRUD操作的方法。然后使用Spring的`@...

    SSH笔试题及答案

    Hibernate 的方法包括使用双向一对多关联,不使用单向一对多、灵活使用单向一对多关联、不用一对一,用多对一取代、配置对象缓存,不使用集合缓存、一对多集合使用 Bag,多对多集合使用 Set、继承类使用显式多态、...

Global site tag (gtag.js) - Google Analytics