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