使用Java註解開發自動產生SQL

來源:互聯網
上載者:User

標籤:import   val   from   select   通過   ati   get   配置   ase   

使用註解開發的好處就是減少設定檔的使用。在實際過程中,隨著項目越來越複雜,功能越來越多,會產生非常多的設定檔。但是,當設定檔過多,實際維護過程中產生的問題就不容易定位,這樣就會徒勞的增加工作量。而使用註解開發,可以減少設定檔的使用,方便代碼的維護,同時,在開發速度上也有大幅提升,因此,學會使用註解開發,是有必要掌握的一項技能。

下面為各位展示下使用註解開發自動產生SQL語句的過程。

首先先定義一個實體類,用於和資料庫欄位進行映射,為了方便,資料庫欄位名稱和實體類變數名稱保持一致。

package com.huawei.andrid.net.annotation;@Table("person")public class Person{@Column("name")private String name;@Column("sex")private String sex;@Column("id")private int id;@Column("age")private int age;public String getName(){return name;}public void setName(String name){this.name = name;}public String getSex(){return sex;}public void setSex(String sex){this.sex = sex;}public int getId(){return id;}public void setId(int id){this.id = id;}public int getAge(){return age;}public void setAge(int age){this.age = age;}}

  下面我們要為這個實體類定義註解,包含@Table和@Column兩個註解。

package com.huawei.andrid.net.annotation;import static java.lang.annotation.ElementType.TYPE;import static java.lang.annotation.RetentionPolicy.RUNTIME;import java.lang.annotation.Documented;import java.lang.annotation.Retention;import java.lang.annotation.Target;@Documented@Retention(RUNTIME)@Target(TYPE)public @interface Table{public String value();}

  元註解:

@Documented  產生javadoc時,支援註解
@Retention(RUNTIME)  註解的生命週期
@Target(TYPE)  註解的在類上

 

package com.huawei.andrid.net.annotation;import static java.lang.annotation.ElementType.FIELD;import static java.lang.annotation.RetentionPolicy.RUNTIME;import java.lang.annotation.Documented;import java.lang.annotation.Retention;import java.lang.annotation.Target;@Documented@Retention(RUNTIME)@Target(FIELD)public @interface Column{public String value();}

  最後,我們需要解析註解,使用java的反射機制。

private static String query(Object p) throws NoSuchMethodException, SecurityException, IllegalAccessException,IllegalArgumentException, InvocationTargetException{StringBuilder str = new StringBuilder();//通過反射擷取Class對象,以便擷取註解的值Class<? extends Object> obj = p.getClass();//判斷該對象的類上有沒有註解@Tableboolean isExistsTable = obj.isAnnotationPresent(Table.class);if (!isExistsTable){return null;}//擷取Table註解,並擷取註解的值,即表名Table table = (Table) obj.getAnnotation(Table.class);String tableName = table.value();//拼裝sqlstr.append("select * from ").append(tableName).append(" where 1=1 ");//擷取所有的成員變數,並遍曆出來成員變數上的註解值Field[] fields = obj.getDeclaredFields();for (Field field : fields){Boolean isExistColumn = field.isAnnotationPresent(Column.class);if (!isExistColumn){continue;}//擷取成員變數上的註解值Column column = field.getAnnotation(Column.class);String columnName = column.value();//擷取成員變數的get方法名String methodName = "get" + columnName.substring(0, 1).toUpperCase() + columnName.substring(1);//擷取成員變數的get方法Method method = obj.getMethod(methodName);//執行成員變數的get方法,參數為該對象Object value = method.invoke(p);//過濾掉成員變數中的null值,以及0if (null == value || (value instanceof Integer && (Integer) value == 0)){continue;}str.append(" and ").append(columnName).append("=").append(value);}return str.toString();}

  測試:

public static void main(String[] args){Person p = new Person();p.setName("wanglu");p.setAge(25);String querySQL = null;try{querySQL = query(p);}catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException| InvocationTargetException e){e.printStackTrace();}System.out.println(querySQL);}

  

使用Java註解開發自動產生SQL

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.