主要使用了反射来获取类信息;使用注解来获取类和数据库表的对应关系
如何创建一条查询语句?
import java.lang.reflect.Field;
/**
* @author jiangli
* @date 2019/11/21 20:17
*/
public class Demo {
public static void main(String[] args)throws Exception{
//通过反射获取类
Class<?> forName = Class.forName("com.java.es.an.People");
// Annotation[] annotations = forName.getAnnotations();
// for (Annotation annotation : annotations) {
// System.out.println(annotation);
// }
//拼接sql
StringBuilder sb =new StringBuilder();
sb.append("select ");
//通过类的成员变量的注解获取数据库表的字段
Field[] fields = forName.getDeclaredFields();
for (int i = 0; i < fields.length; i++) {
SetField setField = fields[i].getAnnotation(SetField.class);
String property = setField.name();
sb.append(property);
if (i == fields.length - 1) {
sb.append(" from ");
}else {
sb.append(" ,");
}
}
//获取表名
SetTable setTable = forName.getAnnotation(SetTable.class);
sb.append(setTable.value()).append(";");
System.out.println(sb.toString());
}
}