java注解实例-反射生成sql

 定义描述用户表的注解:

package dao;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

// 作用域
@Target({ ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME)
public @interface Table {
    String value();
}

 定义描述用户属性的注解:

 1 package dao;
 2 
 3 import java.lang.annotation.ElementType;
 4 import java.lang.annotation.Retention;
 5 import java.lang.annotation.RetentionPolicy;
 6 import java.lang.annotation.Target;
 7 
13 // 作用域
14 @Target({ ElementType.FIELD })
15 @Retention(RetentionPolicy.RUNTIME)
16 public @interface Column {
17     String value();
18 }

定义映射Bean类User:

 1 package dao;
 2 
 3 /**
 4  * 
 5  * 用户表,字段包括:用户ID、用户名、昵称、年龄、性别、所在城市、邮箱、手机号:
 6  * 
 7  * @author 8  */
 9 @Table("user")
10 public class User {
11     @Column("id")
12     private int id;
13 
14     @Column("user_name")
15     private String userName;
16 
17     @Column("nick_name")
18     private String nickName;
19 
20     @Column("age")
21     private int age;
22 
23     @Column("city")
24     private String city;
25 
26     @Column("email")
27     private String email;
28 
29     @Column("mobile")
30     private String mobile;
31 
32     public int getId() {
33         return id;
34     }
35 
36     public void setId(int id) {
37         this.id = id;
38     }
39 
40     public String getUserName() {
41         return userName;
42     }
43 
44     public void setUserName(String userName) {
45         this.userName = userName;
46     }
47 
48     public String getNickName() {
49         return nickName;
50     }
51 
52     public void setNickName(String nickName) {
53         this.nickName = nickName;
54     }
55 
56     public int getAge() {
57         return age;
58     }
59 
60     public void setAge(int age) {
61         this.age = age;
62     }
63 
64     public String getCity() {
65         return city;
66     }
67 
68     public void setCity(String city) {
69         this.city = city;
70     }
71 
72     public String getEmail() {
73         return email;
74     }
75 
76     public void setEmail(String email) {
77         this.email = email;
78     }
79 
80     public String getMobile() {
81         return mobile;
82     }
83 
84     public void setMobile(String mobile) {
85         this.mobile = mobile;
86     }
87 }

根据参数动态返回查询语句:

 1 package dao;
 2 
 3 import java.lang.reflect.Field;
 4 import java.lang.reflect.Method;
 5 
 6 /**
 7  * 根据参数动态返回查询语句
 8  * 
 9  * @author10  */
11 public class ReturnQuery {
12 
13     public static String query(User u1) {
14         StringBuilder str = new StringBuilder();
15         // 1.获取一个类class
16         Class c = u1.getClass();
17         // 2.获取Table的名字
18         boolean exists = c.isAnnotationPresent(Table.class);
19         if (!exists) {
20             return null;
21         }
22         Table t = (Table) c.getAnnotation(Table.class);
23         String tableName = t.value();
24         str.append("select * from ").append(tableName).append("where 1=1");
25         // 3.遍历所有的 字段
26         Field fArray[] = c.getDeclaredFields();
27         for (Field field : fArray) {
28             // 4.处理每个字段对应的sql
29             // 4.1取到字段名
30             boolean fExists = field.isAnnotationPresent(Column.class);// 判断是否包含Column类型的注解
31             if (!fExists) {
32                 continue;
33             }
34             Column column = field.getAnnotation(Column.class);
35             String columnName = column.value();
36             // 4.2取到字段的值
37             String fieldName = field.getName();
38             // 获取相应字段的getXXX()方法
39             String getMethodName = "get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);
40             Object fieldValue=null;
41             try {
42                 Method getMethod = c.getMethod(getMethodName);
43                 fieldValue = getMethod.invoke(u1);
44             } catch (Exception e) {
45                 e.printStackTrace();
46             }
47             //4.3拼接Sql
48             if (fieldValue==null||fieldValue instanceof Integer &&(Integer)fieldValue==0) {
49                 continue;
50             }
51             str.append(" and ").append(fieldName);
52             if (fieldValue instanceof String) {
53                 if (((String) fieldValue).contains(",")) {
54                     String[] values=((String) fieldValue).split(",");
55                     str.append(" in (");
56                     for (String s : values) {
57                         str.append("'").append(s).append("'").append(",");
58                     }
59                     str.deleteCharAt(str.length()-1);
60                     str.append(")");
61                 }else{
62                     str.append("=").append("'").append(fieldValue).append("' ");
63                 }
64             }else {
65                 str.append("=").append(fieldValue);
66             }
67         }
68         return str.toString();
69     }
70 
71 }

测试类:

 1 package dao;
 2 
 3 public class Test {
 4     public static void main(String[] args) {
 5         User u1 = new User();
 6         u1.setId(10); // 查询id
 7 
 8         User u2 = new User();
 9         u2.setUserName("JSFei"); // 模糊查询用户名
10         u2.setAge(21);
11 
12         User u3 = new User();
13         u3.setEmail("123@163.com,123@qq.com"); // 查询邮箱有任意一个的用户
14         
15         String sql1 = ReturnQuery.query(u1);    
16         String sql2 = ReturnQuery.query(u2);    
17         String sql3 = ReturnQuery.query(u3);
18           
19         System.out.println(sql1);  
20         System.out.println(sql2);  
21         System.out.println(sql3);  
22     }
23 }

输出结果:

...............................................

原文地址:https://www.cnblogs.com/save-shengfei/p/5892798.html