Hibernate萬能資料庫訪問程式及其存在問題

2021-08-15 14:46:29 字數 2941 閱讀 7476

建立查詢條件類,並利用反射技術及hibernate框架自帶的criteria類,實現此功能。

查詢類:

public

class

sortandfilterbean ";

private string valuefuzz = "{}";

private string name = "";

private string type = "";

public

intgetbegin()

public

void

setbegin(int begin)

public

intgetend()

public

void

setend(int end)

public string getvalue()

public

void

setvalue(string value)

public string getvaluefuzz()

public

void

setvaluefuzz(string valuefuzz)

public string getname()

public

void

setname(string name)

public string gettype()

public

void

settype(string type)

}

功能實現:

public map getobjectsbycondition(sortandfilterbean sortandfilterbean, class clazz) else 

//指定起始位置及結果最大數

criteria = criteria.setfirstresult(sortandfilterbean.getbegin() - 1);

criteria = criteria.setmaxresults(sortandfilterbean.getend() -sortandfilterbean.getbegin() + 1);

list list = criteria.list();

//復位起始位置及結果最大數,用於獲取所有滿足條件的結果數目

criteria = criteria.setfirstresult(0);

criteria = criteria.setmaxresults(-1);

integer rowtotalcount = integer.valueof(criteria.setprojection(projections.rowcount()).uniqueresult().tostring());

map.put("list",list);

map.put("count",rowtotalcount);

map.put("status",0);

return map;

} catch (dataaccessresourcefailureexception e) catch (hibernateexception e) catch (numberformatexception e)

map.put("status",-1);

return map;

}

查詢實現:

public

class

criteriautil catch (nosuchmethodexception e) catch (illegalacces***ception e) catch (invocationtargetexception e)

//新增索引條件

if(value != null && !value.tostring().equals(""))

}return criteria;

}/**

* 為資料庫查詢增加模糊過濾條件(忽略大小寫),只針對 string 型別條目

*@param criteria 查詢物件

*@param json 搜尋內容,json 格式字串

*@return 增加搜尋條件的查詢物件

*/public

static criteria addfilterconditionfuzz(criteria criteria, string json)

}return criteria;

}}

1.在service層依然需要針對每乙個服務新增資料庫事務注釋,稍微會有點麻煩,可以考慮使用統一命名規則,同時使用aop進行資料庫事務注入,減小工作量;

2.由於是通用規則,如果限制規則沒有處理好,攻擊者可以通過修改請求url及自製json字串,進而篡改不應該被修改的字段。建議不要在使用者及許可權管理等關鍵地方應用此方法;

3.使用反射技術的時候,涉及到拆裝箱的內容要仔細處理,不然容易出現型別不匹配的情況。

事務的實質就是要你運算元據庫時從一而終,要麼全部完成,要麼回滾撤銷所有操作。

在dao層的方法對資料庫的操作通常來說是簡單的,沒業務邏輯性的,所以對於這種加了乙個事務也可以。

但在service層,裡面的方法通常是包含一些複雜邏輯的,乙個方法可能就呼叫了dao的多個方法,所以就必須做到事務管理,要麼service方法裡面的dao方法全部執行,要麼全部撤銷。這樣才能保證資料庫資料的正確性。

所以可以得到如下結論:

同樣,可以根據這個思路將一些需要經常使用到的資料庫操作,寫成通用方法,可以節省開發時間、便於維護,並且能夠有效地防止sql注入問題。

******************************====

******************************====

萬能素材庫 2016萬能高考作文素材大全

2016萬能高考作文素材大全 1 知我者,謂我心憂,不知我者,謂我何求 詩經 王風 黍離 釋義 了解我心情的人,認為我心中惆悵 不了解我心情的,還以為我呆在這兒有什麼要求呢。2 人而無儀,不死何為。詩經風相鼠 釋義 人活著如果不重視禮儀,那麼就如同死人。3 言者無罪,聞者足戒。詩經 大序 釋義 提意...

非標準萬能庫 extc

include include include tree include hash表 include trie樹 include includeusing namespace std using namespace gnu pbds 平衡樹命名空間 可以直接寫平衡樹的命名空間或者是在每個定義結構操作...

萬能資料型別any雜談

萬能資料型別boost any雜談 1 boost any 與 variant t 剛接觸boost any時,不禁讓人想起了 的 variant t類,因為兩者都可以存放其他的型別的值。比較一下兩者可以發現 variant t只能容納 variant 資料型別 詳見 而boost any可以容納用...