讲述Hibernate Utilities

Hibernate还是比较常用的,于是我研究了一下Hibernate Utilities,在这里拿出来和大家分享一下,希望对大家有用。

Hibernate Utilities类

以下代码其中包含了标签文件使用的所有函数,最适合使用 Java 代码编写的代码都被放到了几个 TLD 可以映射的函数中,这样标签文件就可以使用它们了;这些函数都是在Hibernate Utilities 类中进行编码的。因此,我们需要三样东西:定义这些类的 TLD 文件、Hibernate Utilities 中的函数,以及标签文件本身,后者要使用这些函数。(第四样应该是使用这个标签文件的 JSP 页面。)

以下,给出了在 TLD 中引用的函数和另外一个表示给定属性是否是 Date 的方法。在这个类中要涉及到比较多的代码,但是本文限于篇幅,不会给出所有的代码;不过需要注意 findGetterMethod() 除了将表达式语言(Expression Language,EL)方法表示(customer.contact)转换成 Java 表示(customer.getContact())之外,还执行了基本的映像操作。

Hibernate Utilities节选

 
 
 
  1. public static Boolean required(Object object, String propertyPath) {  
  2. Method getMethod = findGetterMethod(object, propertyPath);  
  3. if (getMethod == null) {  
  4. return null;  
  5. } else {  
  6. return getMethod.isAnnotationPresent(NotNull.class);  
  7. }  
  8. }  
  9.  
  10. public static Boolean isDate(Object object, String propertyPath) {  
  11. return java.util.Date.class.equals(getReturnType(object, propertyPath));  
  12. }  
  13.  
  14. public static Class getReturnType(Object object, String propertyPath) {  
  15. Method getMethod = findGetterMethod(object, propertyPath);  
  16. if (getMethod == null) {  
  17. return null;  
  18. } else {  
  19. return getMethod.getReturnType();  
  20. }  

此处可以清楚地看到在运行时使用 Validation annotations 是多么容易。可以简单地引用对象的 getter 方法,并检查这个方法是否有相关的给定的注释 。

【编辑推荐】

  1. 剖析Hibernate Extensions
  2. 介绍Hibernate Iterator方法
  3. Hibernate Session缓存经验总结
  4. 简单介绍Hibernate配置Proxool
  5. 浅谈Hibernate outer-join参数
THE END