首先,我定义了两个自定义注解,Table和Field。
package annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(value={ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface Table {
String value(); //表名
}
先来看Table,这个注解是在运行时读取,因此其保留策略时是RetentionPolicy.RUNTIME,这个注解的主要作用是放在实体类上将实体类映射为数据库中的表名,因此,它的运行目标是ElementType.FIELD。
package annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(value={ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface Field {
String name(); // 数据库字段名
String type(); // 数据字段类型
int length(); // 数据库中字段长度
}
自定义注解Field,主要用于将实体类里面的属性映射为数据库表中的字段信息。 这个注解是在运行时读取,因此其保留策略时是RetentionPolicy.RUNTIME,这个注解主要放在实体类的属性上,因此其运行目标是ElementType.FIELD。
package entity;
import annotation.Field;
import annotation.Table;
@Table("tb_commodity")
public class Commodity {
@Field(name="id", type="integer", length=11)
private int id;
@Field(name = "good_name", type="varchar", length = 30)
private String name;
@Field(name="good_price", type="integer", length=11)
private int price;
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 getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
}
定义一个封装商品表信息的实体类Commodity,用上我们刚刚定义的两个注解。
package core;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import annotation.Table;
public class ProcessAnnotionDemo {
public static void main(String[] args) throws ClassNotFoundException {
Class clazz = Class.forName("entity.Commodity");
for (Annotation annotation : clazz.getAnnotations()) {
if (annotation instanceof Table) {
Table t = (Table)annotation;
System.out.println(t.value());
}
}
for (Field field : clazz.getDeclaredFields()) {
for (Annotation annotation : field.getAnnotations()) {
if (annotation instanceof annotation.Field) {
annotation.Field f = (annotation.Field)annotation;
System.out.println(f.name() + "," + f.type() + "," + f.length());
}
}
}
}
}
通过java的反射,得到实体类 Commodity的注解信息,最终可以将该实体类映射成表名为tb_commodity,字段为good_name,good_price的数据库信息。
运行效果如下图所示



