通过反射和自定义注解实现简单的ORM框架的查询功能

Student类

//注解不仅被保存到class文件中,jvm加载class文件之后,仍然存在,
//通过该注解才能使用反射获取属性
@Retention(RetentionPolicy.RUNTIME)
//自定义数据库的表名
@interface Table {
    String value();
}

@Retention(RetentionPolicy.RUNTIME)
//自定义数据库的列名,长度和类型
@interface Property {

    String name();

    //自定义长度,不写默认是0
    int length() default 0;

    String type();
}

@Table("lzh_student")
public class Student {
    @Property(name="lzh_username",length = 10,type = "varchar")
    private String username;
    @Property(name="lzh_password",length = 10,type = "varchar")
    private String password;

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}

Demo

public class Demo1 {
    public static void main(String[] args) throws Exception {
        Class<?> forName = Class.forName("org.lzh.xxx.Student");
        //获取当前所有的成员变量
        Field[] fields = forName.getDeclaredFields();
        //需要做字符串拼接
        StringBuffer stringBuffer;
        stringBuffer = new StringBuffer();
        stringBuffer.append("select ");
        //遍历
        for (int i = 0; i < fields.length; i++) {
            //得到每一个成员变量
            Field fields1 = fields[i];
            //获取每一个成员变量上的注解
            Property property = fields1.getDeclaredAnnotation(Property.class);
            //得到注解的内容
            stringBuffer.append(property.name());
            //当数组长度减去i大于1的时候需要拼接一个逗号
            if (fields.length - i > 1) {
                stringBuffer.append(",");
            }
        }
        //获取类上注解的内容
        Table table = forName.getDeclaredAnnotation(Table.class);
        stringBuffer.append(" from ").append(table.value());
        System.out.println(stringBuffer.toString());
    }
}

输出:
select lzh_username,lzh_password from lzh_student

 

posted @ 2018-08-11 21:50  奥克兰毛泽西  阅读(243)  评论(0编辑  收藏  举报