自定义注解以及使用注解完成类与表结构的映射关系

*自定义注解:1.使用@interface自定义注解时,自动继承了java.lang.annotation.Annotation接口
 *   2.格式:public @interface 注解名{定义体}
 *   3.其中的每一个方法实际上是声明了一个配置参数:
 *       a.方法的名称就是参数的名称.
 *       b.返回值类型就是参数的类型(返回值类型只能是基本类型、class、string、enum).
 *       c.可以通过default来声明参数的默认值
 *       d.如果只有一个参数成员,一般参数名为value
 *  元注解:作用是负责注解其他注解,java定义了4个标准的meta-annotation类型,
 *    它们被用来提供对其他annotation类型作说明:
 *    @Target 用于描述注解的使用范围,值有PACKAGE(包)、TYPE(类、接口、枚举、Annotation类型)、
 * CONSTRUCTOR(描述构造器)、FIELD(属性)、METHOD(方法)、LOCAL VARLEU(局部变量)、
 * PARAMETER(参数)
 *    @Retention 描述注解的生命周期,值有SOURCE(在源文件中有效)、CLASS(在源文件中有效)、
 *    RUNTIME(运行时有效,可以被反射机制读取)
 *    @Documented
 *    @Inherited
 * 注解只是写出来没多大用处,还要写解析,那才是完整的。

自己写注解来实现类与表结构的映射关系

首先有个类:

public class Student {
   
    private int id;
   
    private String snume;
  
    private int age;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getSnume() {
        return snume;
    }

    public void setSnume(String snume) {
        this.snume = snume;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public Student(int id, String snume, int age) {
        this.id = id;
        this.snume = snume;
        this.age = age;
    }

    public Student(){

    }
}

然后写一个和数据库表名映射的注解:

@Target(value ={ElementType.TYPE} )
@Retention(RetentionPolicy.RUNTIME)
public @interface StudentTable {
    String value();
}

写一个和数据库表信息映射的注解,一般有长度、类型、列名,还有其他,我们就要这三个来写例子:

@Target(value ={ElementType.FIELD} )
@Retention(RetentionPolicy.RUNTIME)
public @interface StudentField {
    String columnName();
    String type();
    int length();
}

然后在Student类中加上注解:

@StudentTable("tb_student")//tb_student是数据库中表名
public class Student {
    @StudentField(columnName = "id",type = "int",length = 10)
    private int id;
    @StudentField(columnName = "sname",type = "varchar",length = 10)
    private String snume;
    @StudentField(columnName = "age",type = "int",length = 3)
    private int age;
......后面省略

当然有解析才是完整的,可以通过反射解析注解。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值