Hibernate ORM模拟实现

今天手动实现了一个小例子,模拟Hibernate将关系型数据库中的记录映射为Java对象的过程,虽然不太实用,但是却很简单明了地说明了映射的过程。下图是这个例子的类图:

我们首先对上面的类图做一个简要的说明,IEntity是一个所有的实体都要实现的接口,它的getDefinition方法返回的是这个实体的定义(EntityDefinition),save方法接受一个java.sql.Connection类型的参数,然后把实体自己保存到数据库中,为简单起见这里没有定义其它数据访问的方法。

EntityDefinition描述了一个实体映射到数据库中表的规则,为了简单起见我在这里设置的规则都是很简单的,它的tableName属性直接说明了它所属于的实体对应的数据库中的表名,实体与它本身的定义是一对一的关系,每一个实体都会持有它自己的定义。另外PropertyDefinition描述的是实体中的属性映射到数据库某个表中的字段的规则,EntityDefinition与它是一对多的关系,因为一个实体会有多个属性对应着数据库中表的多个字段。

AbstractEntity是IEntity的默认实现,此类的名字以Abstract开头是为了说明这个类是为了继承而设计的,那么继承它的子类可以得到什么好处呢?因为子类继承自一个父类就和认干爹差不多,若是没有好处谁情愿做人家的干儿子是不是?我们在此承诺,继承自AbstractEntity的子类不用自己编写任何持久化的代码就能实现将自己保存到数据库中的愿望,它所要做的就是像POJO那样声明一些属性,并在自己定义的包中建立一个如下格式的配置文件:类名.hbm.xml,例如对于Customer类来说,要建立一个Customer.hbm.xml的配置文件,文件的内容和上述类图中提供的类似。

先让我们看看IEntity的源码:

Java代码  
  1. package com.neuqsoft.data.analyse.common;  
  2.   
  3. import java.sql.Connection;  
  4. import java.sql.SQLException;  
  5.   
  6. public interface IEntity {  
  7.     EntityDefinition getDefinition();  
  8.       
  9.     void save(Connection conn)throws SQLException;  
  10. }  

接口中描述的方法都很容易看懂,这里不加赘述,下面是AbstractEntity的源码:

Java代码  
  1. package com.neuqsoft.data.analyse.common;  
  2.   
  3. import java.lang.reflect.Field;  
  4. import java.math.BigDecimal;  
  5. import java.sql.Connection;  
  6. import java.sql.Date;  
  7. import java.sql.PreparedStatement;  
  8. import java.sql.SQLException;  
  9.   
  10. public abstract class AbstractEntity implements IEntity {  
  11.     private EntityDefinition entityDef;  
  12.       
  13.     protected AbstractEntity(){  
  14.         entityDef=new EntityDefinition(getClass());  
  15.     }  
  16.       
  17.     public final void save(Connection conn)throws SQLException{  
  18.         deleteIfExist(conn);//如果记录存在先删除  
  19.         doSave(conn);  
  20.     }  
  21.     private void deleteIfExist(Connection conn)throws SQLException{  
  22.         PropertyDefinition idDefinition=entityDef.getIdDefinition();  
  23.         String deleteSQL="delete from "+entityDef.getTableName()+" where "+idDefinition.getColumnName()+"=?";  
  24.         System.out.println("DELETE:"+deleteSQL);  
  25.         PreparedStatement ps=conn.prepareStatement(deleteSQL);  
  26.         if(ps!=null){  
  27.             setValue(ps,1,idDefinition);  
  28.             ps.executeUpdate();  
  29.             ps.close();  
  30.         }  
  31.     }  
  32.       
  33.     private void setValue(PreparedStatement ps, int index, PropertyDefinition pd)  
  34.         throws SQLException{  
  35.         int type=pd.getType();  
  36.         Object value=getValue(pd.getName());  
  37.         if(type==PropertyDefinition.TYPE_STRING) ps.setString(index,value.toString());  
  38.         else if(type==PropertyDefinition.TYPE_NUMBER) ps.setBigDecimal(index,(BigDecimal)value);  
  39.         else if(type==PropertyDefinition.TYPE_DATE) ps.setDate(index,(Date)value);  
  40.     }  
  41.   
  42.     private Object getValue(String name) {  
  43.         try{  
  44.             Field f=getClass().getDeclaredField(name);  
  45.             f.setAccessible(true);  
  46.             return f.get(this);  
  47.         }catch (Exception e) {  
  48.             throw new RuntimeException(e);  
  49.         }  
  50.     }  
  51.   
  52.     private final void doSave(Connection conn)throws SQLException{  
  53.         PropertyDefinition[] pds=entityDef.getAllPropertyDefinitions();  
  54.         StringBuffer sb=new StringBuffer("insert into "+entityDef.getTableName()+"(");  
  55.         StringBuffer valueBuffer=new StringBuffer("values(");  
  56.         for(int i=0;i<pds.length;i++){  
  57.             sb.append(pds[i].getColumnName());  
  58.             valueBuffer.append("?");  
  59.             if(i<pds.length-1){  
  60.                 sb.append(",");  
  61.                 valueBuffer.append(",");  
  62.             }  
  63.         }  
  64.         String insertSQL=sb.toString()+")"+valueBuffer.toString()+")";  
  65.         System.out.println("INSERT:"+insertSQL);  
  66.         PreparedStatement ps=conn.prepareStatement(insertSQL);  
  67.         if(ps!=null){  
  68.             for(int i=0;i<pds.length;i++) setValue(ps,i+1,pds[i]);  
  69.             ps.executeUpdate();  
  70.             ps.close();  
  71.         }  
  72.     }  
  73.       
  74.     public EntityDefinition getDefinition() {  
  75.         return entityDef;  
  76.     }  
  77. }  

为了实现save(Connection conn)方法,AbstractEntity类定义了几个私有方法,在此做简要说明:

(1)deleteIfExist(Connection conn)throws SQLException 如果实体已经在数据库中存在则首先删除,然后保存,相当于更新操作,判断是否存在的依据是实体的ID,如果实体在数据库中不存在此方法相当于零操作。

(2)setValue(PreparedStatement ps, int index, PropertyDefinition pd) 为PreparedStatement设置参数,目前PropertyDefinition所支持的参数只有三种:字符串String类型,日期Date类型以及数字BigDicemal类型。我们当然可以让它支持更多的类型,这里只支持三种类型只是为了简化起见。

(3)Object getValue(String name) 使用反射机制获取实体某一个属性所对应的属性值,name是声明的属性名,例如Customer类中所声明的private String name。

(4)doSave(Connection conn)throws SQLException 真正将实体保存到数据库中的操作。

AbstractEntity类的构造方法虽然只有一行语句:entityDef=new EntityDefinition(getClass());却是整个系统的关键,因为它初始化了实体的定义,下面让我们看看EntityDefinition的源码:

Java代码  
  1. package com.neuqsoft.data.analyse.common;  
  2.   
  3. import java.net.URL;  
  4. import java.util.Collection;  
  5. import java.util.HashMap;  
  6. import java.util.Iterator;  
  7. import java.util.Map;  
  8.   
  9. import org.dom4j.Document;  
  10. import org.dom4j.Element;  
  11. import org.dom4j.io.SAXReader;  
  12.   
  13. public class EntityDefinition{  
  14.     private String tableName;//实体对应的表  
  15.     public static final String CONFIG_SUFFIX=".hbm.xml";  
  16.     //<实体属性,实体属性的定义>  
  17.     private Map propertyDefMap=new HashMap();  
  18.     //  
  19.     public EntityDefinition(Class clazz) {  
  20.         String configFileName=clazz.getSimpleName()+CONFIG_SUFFIX;  
  21.         URL url=clazz.getResource(configFileName);  
  22.         try{  
  23.             Document document=new SAXReader().read(url.openStream());  
  24.             Element root=document.getRootElement();  
  25.             tableName=root.attribute("tableName").getValue();  
  26.             //mapping property to column of table  
  27.             Iterator propElements=root.elementIterator("Property");  
  28.             while(propElements.hasNext()){  
  29.                 Element element=(Element) propElements.next();  
  30.                 PropertyDefinition pd=new PropertyDefinition(element);  
  31.                 propertyDefMap.put(pd.getName(), pd);  
  32.             }  
  33.         }catch(Exception e){  
  34.             e.printStackTrace();  
  35.             throw new RuntimeException(e);  
  36.         }  
  37.     }  
  38.       
  39.     public PropertyDefinition getIdDefinition(){  
  40.         Iterator it=propertyDefMap.values().iterator();  
  41.         while(it.hasNext()){  
  42.             PropertyDefinition pd=(PropertyDefinition)it.next();  
  43.             if(pd.isId()) return pd;  
  44.         }  
  45.         return null;  
  46.     }  
  47.       
  48.     public PropertyDefinition[] getAllPropertyDefinitions(){  
  49.         Collection cl=propertyDefMap.values();  
  50.         return (PropertyDefinition[]) cl.toArray(new PropertyDefinition[cl.size()]);  
  51.     }  
  52.       
  53.     public String getTableName() {  
  54.         return tableName;  
  55.     }  
  56. }  

显而易见,EntityDefinition是通过获取类似Customer.hbm.xml的配置文件来初始化自己的,它的PropertyDefinition getIdDefinition()方法返回其所属于的实体的ID的PropertyDefinition实例,这里除了isId()方法返回true外,和其它属性的定义没有区别。这里假定每一个实体的配置文件都会指定一个ID,如下所示:<Property name="id" columnName="ID" type="STRING"  isId="true"/>

可以看出EntityDefinition维护着一个Map,这个Map是由实体的属性名映射到其对应的PropertyDefinition(属性定义)。下面是PropertyDefinition的源码:

Java代码  
  1. package com.neuqsoft.data.analyse.common;  
  2.   
  3. import org.dom4j.Element;  
  4.   
  5. public class PropertyDefinition{  
  6.     public static final int TYPE_UNKNOWN=-1;  
  7.     public static final int TYPE_STRING=0;  
  8.     public static final int TYPE_NUMBER=1;  
  9.     public static final int TYPE_DATE=2;  
  10.     private String name;//实体中的属性名  
  11.     private String columnName;//实体相应属性对应表中的列名  
  12.     private int type;//columnName在表中定义的类型  
  13.     private boolean id;//是否是标识符  
  14.     public PropertyDefinition(String name, String columnName, int type) {  
  15.         this.name = name;  
  16.         this.columnName = columnName;  
  17.         this.type = type;  
  18.     }  
  19.     public PropertyDefinition(String name, String columnName, String type){  
  20.         this(name,columnName,analyseType(type));  
  21.     }  
  22.       
  23.     public PropertyDefinition(Element el){  
  24.         setName(el.attributeValue("name"));  
  25.         setColumnName(el.attributeValue("columnName"));  
  26.         setType(analyseType(el.attributeValue("type")));  
  27.         String isIdString=el.attributeValue("isId");  
  28.         boolean isId=(isIdString==null?false:Boolean.valueOf(isIdString).booleanValue());  
  29.         setId(isId);  
  30.     }  
  31.       
  32.     public String getColumnName() {  
  33.         return columnName;  
  34.     }  
  35.     public void setColumnName(String columnName) {  
  36.         this.columnName = columnName;  
  37.     }  
  38.     public String getName() {  
  39.         return name;  
  40.     }  
  41.     public void setName(String name) {  
  42.         this.name = name;  
  43.     }  
  44.     public int getType() {  
  45.         return type;  
  46.     }  
  47.     public void setType(int type) {  
  48.         this.type = type;  
  49.     }  
  50.       
  51.     private static int analyseType(String type) {  
  52.         if("STRING".equalsIgnoreCase(type)) return TYPE_STRING;  
  53.         else if("NUMBER".equalsIgnoreCase(type)) return TYPE_NUMBER;  
  54.         else if("DATE".equalsIgnoreCase(type)) return TYPE_DATE;  
  55.         else return TYPE_UNKNOWN;//Unknown type  
  56.     }  
  57.     public boolean isId() {  
  58.         return id;  
  59.     }  
  60.     public void setId(boolean id) {  
  61.         this.id = id;  
  62.     }  
  63. }  

下面是用于测试的Customer.java以及Customer.hbm.xml的源码:

Java代码  
  1. import java.math.BigDecimal;  
  2.   
  3. import com.neuqsoft.data.analyse.common.AbstractEntity;  
  4.   
  5. public class Customer extends AbstractEntity {  
  6.     private String id;  
  7.     private String name;  
  8.     private BigDecimal age;  
  9.     public BigDecimal getAge() {  
  10.         return age;  
  11.     }  
  12.     public void setAge(BigDecimal age) {  
  13.         this.age = age;  
  14.     }  
  15.     public String getId() {  
  16.         return id;  
  17.     }  
  18.     public void setId(String id) {  
  19.         this.id = id;  
  20.     }  
  21.     public String getName() {  
  22.         return name;  
  23.     }  
  24.     public void setName(String name) {  
  25.         this.name = name;  
  26.     }  
  27. }  
Xml代码  
  1. <Entity tableName="CUSTOMER">  
  2.         <Property name="id" columnName="ID" type="STRING"  isId="true"/>  
  3.         <Property name="name" columnName="NAME" type="STRING"/>  
  4.         <Property name="age" columnName="AGE" type="NUMBER"/>  
  5. </Entity>  
原文地址:https://www.cnblogs.com/jerryxing/p/HIbernate.html