`
snoopy7713
  • 浏览: 1123674 次
  • 性别: Icon_minigender_2
  • 来自: 火星郊区
博客专栏
Group-logo
OSGi
浏览量:0
社区版块
存档分类
最新评论

hibernate 懒加载问题的一个临时解决方案

阅读更多

hibernate的懒加载问题时常会困扰着我们, 今天发现了hibernate自身也提供一些解决办法

Hibernate.initialize(company.getUsers());  这样就加载了users集合

但不支持递归加载

Java代码  收藏代码
  1. it is not guaranteed that the elements INSIDE the collection will be initialized/materialized  

假如这时session关闭了  会报错

 

 

真正解决懒加载还是应该在类的设计 xml文件的配置上下功夫

 

源码:

Java代码  收藏代码
  1. /**  
  2.  * Force initialization of a proxy or persistent collection.  
  3.  * <p/>  
  4.  * Note: This only ensures intialization of a proxy object or collection;  
  5.  * it is not guaranteed that the elements INSIDE the collection will be initialized/materialized.  
  6.  *  
  7.  * @param proxy a persistable object, proxy, persistent collection or <tt>null</tt>  
  8.  * @throws HibernateException if we can't initialize the proxy at this time, eg. the <tt>Session</tt> was closed  
  9.  */   
  10. public   static   void  initialize(Object proxy)  throws  HibernateException {  
  11.     if  ( proxy ==  null  ) {  
  12.         return ;  
  13.     }  
  14.     else   if  ( proxy  instanceof  HibernateProxy ) {  
  15.         ( ( HibernateProxy ) proxy ).getHibernateLazyInitializer().initialize();  
  16.     }  
  17.     else   if  ( proxy  instanceof  PersistentCollection ) {  
  18.         ( ( PersistentCollection ) proxy ).forceInitialization();  
  19.     }  
  20. }  
  21.   
  22. /**  
  23.  * Check if the proxy or persistent collection is initialized.  
  24.  *  
  25.  * @param proxy a persistable object, proxy, persistent collection or <tt>null</tt>  
  26.  * @return true if the argument is already initialized, or is not a proxy or collection  
  27.  */   
  28. public   static   boolean  isInitialized(Object proxy) {  
  29.     if  ( proxy  instanceof  HibernateProxy ) {  
  30.         return  !( ( HibernateProxy ) proxy ).getHibernateLazyInitializer().isUninitialized();  
  31.     }  
  32.     else   if  ( proxy  instanceof  PersistentCollection ) {  
  33.         return  ( ( PersistentCollection ) proxy ).wasInitialized();  
  34.     }  
  35.     else  {  
  36.         return   true ;  
  37.     }  
  38. }  
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics