使用注解完成类和表结构的映射关系

创建注解MyTable,用来注解Stu类

@Target(value={ElementType.TYPE})    TYPE表示只能在类上面注解
@Retention(RetentionPolicy.RUNTIME)
public @interface MyTable {
    String value();
}

创建注解MyField,用来注解Stu的属性

@Target(value={ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface MyField {//Field:字段
    String colName();//列名
    String type();   //类型
    int length();    //长度
    boolean pk();    //主键
    boolean increase();//自增
}

创建学生类MyStu,类名用@MyTable("tb_student")注解,每个属性的内容不一样

比如:id用@MyField(colName="id",length=10,type="int",increase=true,pk=true)注解

package cs.cwnu.test;

@MyTable("tb_student")
public class MyStu {
    @MyField(colName="id",length=10,type="int",increase=true,pk=true)
    private int id;
    @MyField(colName="name",length=10,type="varchar",increase=false,pk=false)
    private String name;
    @MyField(colName="age",length=10,type="int",increase=false,pk=false)
    private int age;
    
    
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    
}

解析注解中的值,与数据库中字段属性对应

//使用反射读取注解信息
@SuppressWarnings("all")//用来清除所有警告的注解
public class Demo {
    public static void main(String[] args) throws NoSuchFieldException, SecurityException  {
        try {
            Class clazz = Class.forName("cs.cwnu.test.MyStu");
            MyTable mt = (MyTable)clazz.getAnnotation(MyTable.class);
            System.out.println("类的注解内容为:"+mt.value());
            Field[] declaredFields = clazz.getDeclaredFields();
            for (Field field : declaredFields) {
                String s = field.getName();
                System.out.println("类的属性为:"+s);
                Field f = clazz.getDeclaredField(s);
                MyField myField = f.getAnnotation(MyField.class);
                System.out.print("列名:"+myField.colName());
                System.out.print("类型:"+myField.type());
                System.out.print("长度:"+myField.length());
                System.out.print("自增:"+myField.increase());
                System.out.print("主键:"+myField.pk());
                System.out.println();
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}

结果显示:

类的注解内容为:tb_student
类的属性为:id
列名:id类型:int长度:10自增:true主键:true
类的属性为:name
列名:name类型:varchar长度:10自增:false主键:false
类的属性为:age
列名:age类型:int长度:10自增:false主键:false

由以上信息,我们可以写sql语句创建数据库。

posted @ 2019-06-28 17:58  疯狂的字母  阅读(531)  评论(0编辑  收藏  举报