java利用註解類比簡單的ORM

來源:互聯網
上載者:User

    源於一個小的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:個人記錄下,這東西改著是挺難的

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.