自定義註解的實踐運用

2021-09-03 07:03:44 字數 2214 閱讀 2875

實體類與資料庫表關聯對映,通過在實體類裡加自定義註解達到構建sql的目的。

有乙個實體類user,裡面定義了一些基本屬性,我在類上和表名上都加上了我自己定義的註解。註解分別為:@table和@column,通過加上註解,我就能知道我要關聯的是哪張表以及實體屬性對應資料庫的哪個字段。

/**

* 建立人:taofut

*/@table("user")

public class user

public void setid(integer id)

public string getusername()

public void setusername(string username)

public string getnickname()

public void setnickname(string nickname)

public integer getage()

public void setage(integer age)

public string getcity()

public void setcity(string city)

public string getemail()

public void setemail(string email)

public string getmobile()

public void setmobile(string mobile)

}

下面我先建立一下自定義註解@table和@column。

/**

* 建立人:taofut

*/@target(elementtype.type)

@retention(retentionpolicy.runtime)

public @inte***ce table

/** * 建立人:taofut

*/@target(elementtype.field)

@retention(retentionpolicy.runtime)

public @inte***ce column

最後,我需要通過自定義註解來達到組裝sql語句的目的。

/**

* 建立人:taofut

*/public class test

private static string query(filter filter)

table tb=(table)c.getannotation(table.class);

string tablename=tb.value();

//2.通過自定義註解拿到資料庫字段

先獲取所有字段

field fields=c.getdeclaredfields();

for(field field:fields)

取得欄位名

column column=(column) field.getannotation(column.class);

string fname=column.value();

取得字段值

string fieldname=field.getname();

string methodname="get"+fieldname.substring(0,1).touppercase()+fieldname.substring(1);

object fieldvalue=null;

try

if(fieldvalue instanceof integer)else if(fieldvalue instanceof string)

} catch (exception e)

}return sql.tostring();

}}

輸出結果:

select * from user where 1=1 and id=10 and age=27

select * from user where 1=1 and username=『taofut』

select * from user where 1=1 and email=『1887495****@163.com』

歸根結底,就是通過反射拿到註解上的值(資料庫欄位名稱),又通過反射去呼叫get方法獲取屬性值。sql語句拼接好了,就可以給jdbc去呼叫了。

自定義註解

target elementtype.field retention retentionpolicy.runtime public inte ce setvalue以上就是乙個自定義的註解,下面來進行說明。target elementtype.field 表示支援該註解的程式元素,field就是屬性...

自定義註解

三個重要元註解 target 即註解的作用域,用於說明註解的使用範圍 即註解可以用在什麼地方,比如類的註解,方法註解,成員變數註解等等 elemenettype.constructor 構造器宣告 elemenettype.field 域宣告 包括 enum 例項 elemenettype.loca...

自定義註解

三個重要元註解 target 即註解的作用域,用於說明註解的使用範圍 即註解可以用在什麼地方,比如類的註解,方法註解,成員變數註解等等 elemenettype.constructor 構造器宣告 elemenettype.field 域宣告 包括 enum 例項 elemenettype.loca...