package com.ann.test; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Inherited; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * 字段自定义注解 */ @Target({ElementType.FIELD}) @Retention(RetentionPolicy.RUNTIME) @Inherited @Documented public @interface Column { String value(); }
package com.ann.test; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Inherited; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * 表自定义注解 */ @Target({ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) @Inherited @Documented public @interface Table { String value(); }
package com.ann.test; /** * 用户实体使用注解 */ @Table("user") public class User { @Column("id") private int id; @Column("userName") private String userName; @Column("sex") private int sex; @Column("mobile") private String mobile; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public int getSex() { return sex; } public void setSex(int sex) { this.sex = sex; } public String getMobile() { return mobile; } public void setMobile(String mobile) { this.mobile = mobile; } }
package com.ann.test; import java.lang.reflect.Field; import java.lang.reflect.Method; /** * 模拟实体到数据库表字段的测试 */ public class Test { public static void main(String[] args) { User u = new User(); u.setUserName("张三"); u.setSex(1); System.out.println(parseUser(u)); } public static String parseUser(User u){ StringBuffer sb = new StringBuffer(); sb.append("select * from "); try { //1.1使用类加载器加载类, 获取表名 Class c = Class.forName("com.ann.test.User"); //1.2找到类上的注解,并拿到注解实例 if(c.isAnnotationPresent(Table.class)){ Table t = (Table)c.getAnnotation(Table.class); String tableName = t.value(); sb.append(tableName); } sb.append(" where 1=1"); //2.获取字段名与值 Field[] fs = c.getDeclaredFields(); for(Field f : fs){ //2.1字段名 String column = ""; if(f.isAnnotationPresent(Column.class)){ Column fld = (Column)f.getAnnotation(Column.class); column = fld.value(); } //2.2字段值 String fieldName = f.getName(); String getMethod = "get"+fieldName.substring(0, 1).toUpperCase()+fieldName.substring(1); Method method = c.getMethod(getMethod); Object fieldValue = method.invoke(u); if(fieldValue instanceof Integer && (Integer)fieldValue == 0){ continue; } if(fieldValue != null){ sb.append(" and ").append(column).append("="); if(fieldValue instanceof String){ sb.append("'").append(fieldValue).append("'"); }else{ sb.append(fieldValue); } } } } catch (Exception e) { e.printStackTrace(); } return sb.toString(); } }
输出结果:
select * from user where 1=1 and userName='张三' and sex=1