Sunday, January 24, 2016

Full Example of declare and use an annotation

To see the basic concept of Annotation: here
To see the basic concept of declare an Annotation: here

Goal:
Declare table and field annotation for SQL database, so when we can build ORM(Object Relationship Mapping)

SQLTable Annotation:
@Target(value=ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface SQLTable {
 String value(); //table name
}

SQLField Annotation:
@Target(value=ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface SQLField {
 String column();
 String type();
 int length();
}
Table structure

A Model class using annotations as description
@SQLTable("student")
public class Student {
 @SQLField(column="id",type="int",length=10)
 private int id;
 @SQLField(column="name",type="varchar",length=10)
 private String studentName;
 @SQLField(column="age",type="int",length=3)
 private int age;
 public int getId() {
  return id;
 }
 public void setId(int id) {
  this.id = id;
 }
 public String getStudentName() {
  return studentName;
 }
 public void setStudentName(String studentName) {
  this.studentName = studentName;
 }
 public int getAge() {
  return age;
 }
 public void setAge(int age) {
  this.age = age;
 }
 
}


Use Annotation to build SQL:


public class Demo2 {
 @Test
 public void test(){
  try{
   Class clazz = Class.forName("model.Student");
   
   //(1)get all annotations for the class
   Annotation[] annotations = clazz.getAnnotations();
   for(Annotation a: annotations){
    System.out.println(a);
   }
   //(1) get the specified annotation for the class
   SQLTable table = (SQLTable) clazz.getAnnotation(SQLTable.class);
   System.out.println(table);
   
   //(2) get annotation for the field
   Field f = clazz.getDeclaredField("studentName"); //get the target field from class
   SQLField myField = f.getAnnotation(SQLField.class); //get the annotation for this field
   //use function declared in annotation
   System.out.println(myField.column()+","+myField.type()+","+myField.length());  
   
   //based on (1) and (2), we can build up all info for the related sql table   
   
  }catch(Exception e){
   
  }
 }
}

No comments:

Post a Comment