java利用注解模拟简单的ORM

    源于一个小的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:个人记录下,这东西改着是挺难的

原文地址:https://www.cnblogs.com/GYoungBean/p/2827723.html