java利用注解模拟简单的ORM

本文介绍了一种使用注解处理数据库字段与属性不一致的方法,通过自定义注解来映射数据库字段到Bean属性,简化了数据库操作与对象映射过程。此外,文章还讨论了注解的优缺点,并提出了解决注解过多导致性能下降的策略。

    源于一个小的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/archive/2012/12/21/2827723.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值