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();
}
}

你可能感兴趣的:(Hibernate)