源於一個小的DAO組件,內容很簡單是基於Bonecp的JDBC工具,但是項目裡常常會遇到資料庫欄位與屬性不一致的情況,在利用反射和內省建立BEAN時就比較麻煩。開始考慮使用設定檔,但是想想設定檔還是比較坑爹的,最後採用註解的方式。
工具類很簡單,但對於簡單業務還是比較方便的。代碼如下:
import java.lang.annotation.ElementType;import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.annotation.Target;@Retention(RetentionPolicy.RUNTIME)@Target( { ElementType.FIELD })public @interface AttrTransform { public String col(); public String property();}
註解中col用來標示資料庫端欄位名,property用來標示Bean內屬性。註解處理代碼如下:
/** * 列對照 * @param propertyName 屬性名稱 * @param type 類 * @return */ public static String propertyToCol(String propertyName,Class<?> type){ if(null!=type){ Field[] field = type.getDeclaredFields(); Annotation ann = null; for (Field f : field) { ann = f.getAnnotation(AttrTransform.class); if(ann!=null){ AttrTransform at = (AttrTransform)ann; if(propertyName.equalsIgnoreCase(at.property())){ return at.col(); } } } } return propertyName; } /** * 屬性對照 * @param propertyName 列名稱 * @param type 類 * @return */ public static String colToProperty(String colName,Class<?> type){ if(null!=type){ Field[] field = type.getDeclaredFields(); Annotation ann = null; for (Field f : field) { ann = f.getAnnotation(AttrTransform.class); if(ann!=null){ AttrTransform at = (AttrTransform)ann; if(colName.equalsIgnoreCase(at.col())){ return at.property(); } } } } return colName; }
如上所示,考慮到註解過多時候會比較慢,所以可以在建立類註解或其他標示然後將註解緩衝起來。
PS:個人記錄下,這東西改著是挺難的