注解
- 定义Table:
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface Table{
String value();
}
-
- 定义Column:
@Target({ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface Column{
String value();
}
注解的实体类
@Table("user")
public class Filter {
@Column("id")
private int id;
@Column("userName")
private String userName;
@Column("nickName")
private String nickName;
@Column("age")
private int age;
@Column("city")
private String city;
@Column("email")
private String email;
@Column("mobile")
private String mobile;
//setter\getter
}
读取注解
public class TestF {
public static void main(String[] args) throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
Filter f1=new Filter();
f1.setId(10);
f1.setUserName("link");
f1.setEmail("linmin@qq.com");
String sql1=query(f1);
System.out.println(sql3);
}
public static String query(Filter f) throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException{
StringBuilder sb=new StringBuilder();
//获取类类型
Class c=f.getClass();
//判断Table注解是否存在
boolean exist=c.isAnnotationPresent(Table.class);
if(!exist){
return null;
}
//获取注解名
Table t=(Table) c.getAnnotation(Table.class);
String tableName=t.value();
//获取字段
Field[] m=c.getDeclaredFields();
for(Field field:m){
boolean fexist=field.isAnnotationPresent(Column.class);
if(!exist){
continue;
}
//获取字段的column注解名
Column column=field.getAnnotation(Column.class);
String columnName=column.value();
//获取字段名
String fieldName=field.getName();
//执行相应的方法获取字段值
String getMethodName="get"+fieldName.substring(0, 1).toUpperCase()+fieldName.substring(1);
Object fieldValue=null;
Method getMethod=c.getMethod(getMethodName);
fieldValue=getMethod.invoke(f);
sb.append("and").append(fieldName).append("=");
if(fieldValue!=null){
sb.append(fieldValue);
}
}
return sb.toString();
}
}