【转】hibernate动态创建表,修改表字段
我们知道,hibernate的tool工具中有个包hbm2ddl可以通过hibernate的映射文对数据库进行ddl操作,而在配置文件中加 入<property name="hbm2ddl.auto">update</property>,就可以根据映射文件进行ddl操作了。
那我们要在运行创建表,或修改表的字段,那我们可以先通过DOM修改配置文件来间接修改数据库
那要创建数据库表的话,只要创建了新的映射文件,并通过映射文件进行插入操作,就可以创建表了
那我们要修改数据库表的字段怎么办呢?
hibernate3.0中给我们提供了动态组件的功能,这种映射的优点是通过修改映射文件,就可以在部署时检测真实的属性的能力,所以就可以通过DOM在运行时操作映射文件,这样就修改了属性,当查入一条新的数据了,就可以删除或添加新的字段了
下面贴出我写的一些代码
hibernate的配置文件:
<session-factory>
<propertyname="myeclipse.connection.profile">Oracle</property>
<propertyname="connection.url">
jdbc:oracle:thin:@192.168.1.52:1521:orclp
</property>
<propertyname="connection.username">transys</property>
<propertyname="connection.password">transys</property>
<propertyname="connection.driver_class">
oracle.jdbc.driver.OracleDriver
</property>
<propertyname="format_sql">true</property>
<propertyname="dialect">
org.hibernate.dialect.Oracle9Dialect
</property>
<propertyname="current_session_context_class">thread</property>
<propertyname="show_sql">true</property>
<propertyname="hbm2ddl.auto">update</property>
</session-factory>
</hibernate-configuration>
映射文件:
<classabstract="false"name="com.tough_tide.evau.edu_hall.model.EduHallData"entity-name="EDU_HALL_DATA_01"table="EDU_HALL_DATA_01"schema="TRANSYS">
<idname="eduHallDataId"type="java.lang.String">
<columnname="EDU_HALL_DATA_ID"length="20"/>
<generatorclass="sequence">
<paramname="sequence">
EDU_HALL_DATA_01_SEQ
</param>
</generator>
</id>
<propertyname="sysDeptId"type="java.lang.String">
<columnname="SYS_DEPT_ID"length="20"not-null="true"/>
</property>
<propertyname="sysUserInfoId"type="java.lang.String">
<columnname="SYS_USER_INFO_ID"length="20"not-null="true"/>
</property>
<dynamic-componentinsert="true"name="dataProperties"optimistic-lock="true"unique="false"update="true">
</dynamic-component>
</class>
修改hibernate中实体属性的类:
publicclassHibernateEntityManager{
privateComponententityProperties;
//实体类
privateClassentityClass;
//实体名称
privateStringentityName;
//动态组件名称
privateStringcomponentName;
//映射文件名
privateStringmappingName;
publicStringgetMappingName(){
returnmappingName;
}
publicvoidsetMappingName(StringmappingName){
this.mappingName=mappingName;
}
publicHibernateEntityManager(StringentityName,StringcomponentName,StringmappingName){
this.entityName=entityName;
this.componentName=componentName;
this.mappingName=mappingName;
}
publicHibernateEntityManager(ClassentityClass,StringcomponentName,StringmappingName){
this.entityClass=entityClass;
this.componentName=componentName;
this.mappingName=mappingName;
}
publicComponentgetEntityProperties(){
if(this.entityProperties==null){
Propertyproperty=getPersistentClass().getProperty(componentName);
this.entityProperties=(Component)property.getValue();
}
returnthis.entityProperties;
}
/**
*添加字段
*@paramname添加的字段
*@paramtype字段的类型
*/
publicvoidaddEntityField(Stringname,Classtype){
SimpleValuesimpleValue=newSimpleValue();
simpleValue.addColumn(newColumn(name));
simpleValue.setTypeName(type.getName());
PersistentClasspersistentClass=getPersistentClass();
simpleValue.setTable(persistentClass.getTable());
Propertyproperty=newProperty();
property.setName(name);
property.setValue(simpleValue);
getEntityProperties().addProperty(property);
updateMapping();
}
/**
*添加多个字段
*@paramlist
*/
publicvoidaddEntityField(List<FieldInfo>list){
for(FieldInfofi:list){
addEntityField(fi);
}
updateMapping();
}
privatevoidaddEntityField(FieldInfofi){
StringfieldName=fi.getFieldName();
StringfieldType=fi.getFieldType().getName();
SimpleValuesimpleValue=newSimpleValue();
simpleValue.addColumn(newColumn(fieldName));
simpleValue.setTypeName(fieldType);
PersistentClasspersistentClass=getPersistentClass();
simpleValue.setTable(persistentClass.getTable());
Propertyproperty=newProperty();
property.setName(fieldName);
property.setValue(simpleValue);
getEntityProperties().addProperty(property);
}
/**
*删除字段
*@paramname字段名称
*/
publicvoidremoveEntityField(Stringname){
Iterator<Property>propertyIterator=getEntityProperties().getPropertyIterator();
while(propertyIterator.hasNext()){
Propertyproperty=propertyIterator.next();
if(property.getName().equals(name)){
propertyIterator.remove();
updateMapping();
return;
}
}
}
privatesynchronizedvoidupdateMapping(){
HibernateMappingManagerhmm=newHibernateMappingManager();
hmm.updateClassMapping(this);
}
privatePersistentClassgetPersistentClass(){
if(entityClass==null){
returnHibernateSessionFactory.getClassMapping(entityName);
}else{
returnHibernateSessionFactory.getConfiguration().getClassMapping(entityClass.getName());
}
}
publicStringgetEntityName(){
returnentityName;
}
publicvoidsetEntityName(StringentityName){
this.entityName=entityName;
}
publicvoidsetEntityProperties(ComponententityProperties){
this.entityProperties=entityProperties;
}
publicClassgetEntityClass(){
returnentityClass;
}
publicvoidsetEntityClass(ClassentityClass){
this.entityClass=entityClass;
}
publicStringgetComponentName(){
returncomponentName;
}
publicvoidsetComponentName(StringcomponentName){
this.componentName=componentName;
}
}
通过DOM修改映射文件的类:
publicclassHibernateMappingManager{
/**
*更新映射文件
*@parammappingName映射文件名
*@parampropertiesList映射文件的数据
*/
publicvoidupdateClassMapping(StringmappingName,List<Map<String,String>>propertiesList){
try{
Stringfile=EduHallData.class.getResource(mappingName).getPath();
Documentdocument=XMLUtil.loadDocument(file);
NodeListcomponentTags=document.getElementsByTagName("dynamic-component");
Nodenode=componentTags.item(0);
XMLUtil.removeChildren(node);
for(Map<String,String>map:propertiesList){
Elementelement=creatPropertyElement(document,map);
node.appendChild(element);
}
//XMLUtil.saveDocument(document,file);
XMLUtil.saveDocument(null,null);
}catch(DOMExceptione){
//TODOAuto-generatedcatchblock
e.printStackTrace();
}catch(ParserConfigurationExceptione){
//TODOAuto-generatedcatchblock
e.printStackTrace();
}catch(SAXExceptione){
//TODOAuto-generatedcatchblock
e.printStackTrace();
}catch(IOExceptione){
//TODOAuto-generatedcatchblock
e.printStackTrace();
}catch(TransformerExceptione){
e.printStackTrace();
}
}
/**
*更新映射文件
*@paramhemHibernateEntityMananger实例
*/
publicvoidupdateClassMapping(HibernateEntityManagerhem){
try{
Stringfile=EduHallData.class.getResource(hem.getMappingName()).getPath();
//Configurationcon=HibernateSessionFactory.getConfiguration();
//con.addResource(file);
//PersistentClasspc=HibernateSessionFactory.getClassMapping("EDU_HALL_DATA_01");
Documentdocument=XMLUtil.loadDocument(file);
NodeListcomponentTags=document.getElementsByTagName("dynamic-component");
Nodenode=componentTags.item(0);
XMLUtil.removeChildren(node);
IteratorpropertyIterator=hem.getEntityProperties().getPropertyIterator();
while(propertyIterator.hasNext()){
Propertyproperty=(Property)propertyIterator.next();
Elementelement=creatPropertyElement(document,property);
node.appendChild(element);
}
XMLUtil.saveDocument(document,file);
}catch(DOMExceptione){
//TODOAuto-generatedcatchblock
e.printStackTrace();
}catch(ParserConfigurationExceptione){
//TODOAuto-generatedcatchblock
e.printStackTrace();
}catch(SAXExceptione){
//TODOAuto-generatedcatchblock
e.printStackTrace();
}catch(IOExceptione){
//TODOAuto-generatedcatchblock
e.printStackTrace();
}catch(TransformerExceptione){
e.printStackTrace();
}
}
privateElementcreatPropertyElement(Documentdocument,Propertyproperty){
Elementelement=document.createElement("property");
Typetype=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));
returnelement;
}
privateElementcreatPropertyElement(Documentdocument,Map<String,String>map){
Elementelement=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));
returnelement;
}
/**
*修改映射文件的实体名和表名
*@parammappingName
*@paramentityName
*/
publicvoidupdateEntityName(StringmappingName,StringentityName){
Stringfile=EduHallData.class.getResource(mappingName).getPath();
try{
Documentdocument=XMLUtil.loadDocument(file);
NodeListnodeList=document.getElementsByTagName("class");
Elementelement=(Element)nodeList.item(0);
element.setAttribute("entity-name",entityName);
element.setAttribute("table",entityName);
nodeList=document.getElementsByTagName("param");
ElementelementParam=(Element)nodeList.item(0);
XMLUtil.removeChildren(elementParam);
Texttext=document.createTextNode(entityName+"_SEQ");
elementParam.appendChild(text);
XMLUtil.saveDocument(document,file);
}catch(ParserConfigurationExceptione){
//TODOAuto-generatedcatchblock
e.printStackTrace();
}catch(SAXExceptione){
//TODOAuto-generatedcatchblock
e.printStackTrace();
}catch(IOExceptione){
//TODOAuto-generatedcatchblock
e.printStackTrace();
}catch(TransformerExceptione){
e.printStackTrace();
}
}
/**
*更新hibernate的配置文件
*@paramargs
*/
publicvoidupdateHibernateConfig(StringconfigName,StringmappingName){
Stringfile=Thread.currentThread().getContextClassLoader().getResource(configName).getPath();
Stringresource=EduHallData.class.getResource(mappingName).toString();
StringclassPath=Thread.currentThread().getContextClassLoader().getResource("").toString();
resource=resource.substring(classPath.length());
try{
Documentdocument=XMLUtil.loadDocument(file);
NodeListnodeList=document.getElementsByTagName("session-factory");
Elementelement=(Element)nodeList.item(0);
ElementelementNew=document.createElement("mapping");
elementNew.setAttribute("resource",resource);
Texttext=document.createTextNode("");
element.appendChild(text);
element.appendChild(elementNew);
XMLUtil.saveDocument(document,file);
//XMLUtil.saveDocument(null,null);
}catch(ParserConfigurationExceptione){
//TODOAuto-generatedcatchblock
e.printStackTrace();
}catch(SAXExceptione){
//TODOAuto-generatedcatchblock
e.printStackTrace();
}catch(IOExceptione){
//TODOAuto-generatedcatchblock
e.printStackTrace();
}catch(TransformerExceptione){
e.printStackTrace();
}
}
}
DOM工具类:
publicclassXMLUtil{
publicstaticvoidremoveChildren(Nodenode){
NodeListchildNodes=node.getChildNodes();
intlength=childNodes.getLength();
for(inti=length-1;i>-1;i--){
node.removeChild(childNodes.item(i));
}
}
publicstaticDocumentloadDocument(Stringfile)
throwsParserConfigurationException,SAXException,IOException{
DocumentBuilderFactoryfactory=DocumentBuilderFactory.newInstance();
DocumentBuilderbuilder=factory.newDocumentBuilder();
returnbuilder.parse(file);
}
publicstaticvoidsaveDocument(Documentdom,Stringfile)
throwsTransformerConfigurationException,
FileNotFoundException,
TransformerException,
IOException{
TransformerFactorytf=TransformerFactory.newInstance();
Transformertransformer=tf.newTransformer();
transformer.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC,dom.getDoctype().getPublicId());
transformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM,dom.getDoctype().getSystemId());
DOMSourcesource=newDOMSource(dom);
StreamResultresult=newStreamResult();
FileOutputStreamoutputStream=newFileOutputStream(file);
result.setOutputStream(outputStream);
transformer.transform(source,result);
outputStream.flush();
outputStream.close();
}
}