講述Hibernate Utilities
Hibernate還是比較常用的,于是我研究了一下Hibernate Utilities,在這里拿出來和大家分享一下,希望對大家有用。
Hibernate Utilities類
以下代碼其中包含了標簽文件使用的所有函數(shù),最適合使用 Java 代碼編寫的代碼都被放到了幾個 TLD 可以映射的函數(shù)中,這樣標簽文件就可以使用它們了;這些函數(shù)都是在Hibernate Utilities 類中進行編碼的。因此,我們需要三樣東西:定義這些類的 TLD 文件、Hibernate Utilities 中的函數(shù),以及標簽文件本身,后者要使用這些函數(shù)。(第四樣應該是使用這個標簽文件的 JSP 頁面。)
以下,給出了在 TLD 中引用的函數(shù)和另外一個表示給定屬性是否是 Date 的方法。在這個類中要涉及到比較多的代碼,但是本文限于篇幅,不會給出所有的代碼;不過需要注意 findGetterMethod() 除了將表達式語言(Expression Language,EL)方法表示(customer.contact)轉(zhuǎn)換成 Java 表示(customer.getContact())之外,還執(zhí)行了基本的映像操作。
Hibernate Utilities節(jié)選
- public static Boolean required(Object object, String propertyPath) {
- Method getMethod = findGetterMethod(object, propertyPath);
- if (getMethod == null) {
- return null;
- } else {
- return getMethod.isAnnotationPresent(NotNull.class);
- }
- }
- public static Boolean isDate(Object object, String propertyPath) {
- return java.util.Date.class.equals(getReturnType(object, propertyPath));
- }
- public static Class getReturnType(Object object, String propertyPath) {
- Method getMethod = findGetterMethod(object, propertyPath);
- if (getMethod == null) {
- return null;
- } else {
- return getMethod.getReturnType();
- }
- }
此處可以清楚地看到在運行時使用 Validation annotations 是多么容易??梢院唵蔚匾脤ο蟮?getter 方法,并檢查這個方法是否有相關(guān)的給定的注釋 。
【編輯推薦】