需求:
使用注解完成类和表结构的映射关系,
表名为:tb_student
表结构:
id int(10)
name varchar(10)
age int(3)
自定义注解类Table ,注解表名
package study_09;
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(value=RetentionPolicy.RUNTIME)
public @interface Table {
String value();//只有一个参数建议起名value
}
自定义注解类StudentField,注解属性
package study_09;
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(value=RetentionPolicy.RUNTIME)
public @interface StudentField {
String columnName();//表格字段名
String type();//字段类型
int length();//字段长度
}
student类
package study_09;
@Table(value="tb_student")//设定表名
public class Student {
@StudentField(columnName="sname",length=10,type="varchar")//设定字段的属性
private String studentName;
@StudentField(columnName="age",length=3,type="int")
private int age;
@StudentField(columnName="id",length=10,type="int")
private int 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;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
现在注解完毕,开始使用反射读取注解信息
package study_09;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
public class Reflect01 {
public static void main(String[] args) throws NoSuchFieldException, SecurityException {
try {
Class clz = Class.forName("study_09.Student");
//获得这个类的所有注解
Annotation[] annotations = clz.getAnnotations();
for (Annotation annotation : annotations) {
System.out.println(annotation);
}
//获得类的指定注解
Table st = (Table)clz.getAnnotation(Table.class);
System.out.println(st.value());
//获得类的属性注解
Field field = clz.getDeclaredField("studentName");//获取指定的字段
StudentField stField = field.getAnnotation(StudentField.class);
System.out.println(stField.columnName() + "------->" + stField.length() + "------>" + stField.type());//获取属性
//根据获得表名和字段信息拼出SQL语句
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
@study_09.Table(value=tb_student)
tb_student
sname------->10------>varchar