注解Table
package annotation;import java.lang.annotation.Documented;import java.lang.annotation.ElementType;import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.annotation.Target;import javax.lang.model.element.Element;@Documented@Retention(RetentionPolicy.RUNTIME)@Target(ElementType.TYPE)public @interface Table { public String tableName(); public String schema() default "b3blog";}
注解Column
package annotation;import java.lang.annotation.Documented;import java.lang.annotation.ElementType;import java.lang.annotation.Inherited;import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.annotation.Target;@Inherited@Documented@Target(ElementType.FIELD)@Retention(RetentionPolicy.RUNTIME)public @interface Column { public String value();}
定义一个实体User
package model;import annotation.Column;import annotation.Table;@Table(tableName="solo_user")public class User { @Column("id") private Integer id; @Column("name") private String name; @Column("sex") private Integer sex; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getSex() { return sex; } public void setSex(Integer sex) { this.sex = sex; } }
测试类Test
package javaassist;import java.lang.annotation.Annotation;import java.lang.reflect.Field;import model.User;import annotation.Column;import annotation.Table;public class Test { public static void main(String[] args) throws Exception { //得到所有的注解 Annotation[] annotations=User.class.getAnnotations(); for (int i = 0; i < annotations.length; i++) { //判断注解类型 if (annotations[i].annotationType().equals(Table.class)) { Table tableAnnotation=(Table) annotations[i]; System.out.println("表名称:"+tableAnnotation.tableName()); System.out.println("schema默认值:"+tableAnnotation.schema()); } } Field[] fields=User.class.getDeclaredFields(); for (Field field : fields) { Column columnAnnotation=field.getAnnotation(Column.class); if (columnAnnotation!=null) { System.out.println("字段名称:"+field.getName()+" 注解value:"+columnAnnotation.value()); } } }}
运行结果
表名称:solo_userschema默认值:b3blog字段名称:id 注解value:id字段名称:name 注解value:name字段名称:sex 注解value:sex