定义表名注解
package com.example.demo.learn.orm;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
/**
* 表的别名
* 项目中使用注解,肯定会使用反射,反射应用场景, jdbc spring ioc 常用的框架, 注解实现
*/
@Retention(RetentionPolicy.RUNTIME)
public @interface SetTable {
String value();
}
定义描述表字段注解
package com.example.demo.learn.orm;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@Retention(RetentionPolicy.RUNTIME)
public @interface SetProperty {
String name();
int length();
}
使用注解
package com.example.demo.learn.orm;
/**
* 表示用户对应的实体类
*/
@SetTable("t_tag")
public class UserEntity {
@SetProperty(name = "user_name", length = 20)
private String userName;
@SetProperty(name = "age", length = 10)
private Integer age;
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
@Override
public String toString() {
return "UserEntity{" +
"userName='" + userName + '\'' +
", age=" + age +
'}';
}
}
实现ORM框架映射,通过使用注解和反射机制
package com.example.demo.learn.orm;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
public class Test {
private static String path = "com.example.demo.learn.orm.UserEntity";
public static void main(String[] args) throws ClassNotFoundException {
Class<?> objClass = Class.forName(path);
/**
* 表示该类上面使用的注解,只会获取到当前类上使用的注解
*/
Annotation[] annotations = objClass.getAnnotations();
for (Annotation annotation : annotations) {
System.out.println(annotation);
}
/**
*获取某个注解对象,以及注解上的值
*/
SetTable setTable = objClass.getAnnotation(SetTable.class);
// 表的名称
String tabName = setTable.value();
// 所有实体类属性
Field[] fields = objClass.getDeclaredFields();
StringBuffer buffer = new StringBuffer();
buffer.append("select ");
for (int i = 0; i < fields.length; i++) {
SetProperty property = fields[i].getAnnotation(SetProperty.class);
String name = property.name();
buffer.append(name);
if (i == fields.length-1) {
buffer.append(" from ");
} else {
buffer.append(" , ");
}
}
buffer.append(tabName);
System.out.println(buffer.toString());
}
}