簡體   English   中英

每次獲取Lazy OneToMany集合

[英]Every time fetched Lazy OneToMany collection

我有一個擁有一組神經科醫療記錄的患者。

患者分類結構如下:

@Entity
@Table(name = "patient")
public class PatientEntity {

   //other properties

   @OneToMany(fetch = FetchType.LAZY, mappedBy = "patient")
   private Set<NeurologicalFindingEntity> neurologicalFindingList;

   public Set<NeurologicalFindingEntity> getNeurologicalFindingList() {        
    return neurologicalFindingList; //DEBUGGER never got to this line
   }

   //other get and set methods
}

NeurologicalFinding類的結構如下:

@Entity
@Table(name = "neurological_finding")
public class NeurologicalFindingEntity{

   //other properties

   @ManyToOne
   @JoinColumn(name = "patient_id")
   private PatientEntity patient;

   //get and set methods
}

在我的應用中,我想使用DAO的以下方法通過ID來獲取患者,而無需他的NeurologicalFinding記錄:

public PatientEntity getPatientById(int patientId) {      

   Criteria criteria = sessionFactory.getCurrentSession()
            .createCriteria(PatientEntity.class);

   criteria.add(Restrictions.eq("id", patientId));

   return (PatientEntity) criteria.uniqueResult();
}

當我使用這種方法時,我仍然對他的NeurologicalFinding記錄感到耐心。 永遠不會調用集合的getter(通過調試器進行檢查),所以當沒有人要求時,如何加載惰性集合?

如果您需要有關我的應用的更多信息,我可以為您提供。

對於這種情況,您可以使用EntityManager.find()代替條件查詢。 其次,您可以嘗試將注釋放在setter而不是字段上。 第三,您還可以在關系的另一端指定fetch=LAZY ,但是我認為這不是您所需要的。

最后,我的經驗發現(盡管這適用於EclipseLink,不一定適用於Hibernate)是為了支持延遲獲取,有時需要字節碼編織。 每個JPA提供程序通常都有一個用於此目的的工具(以及一個Ant任務和一個Maven插件)。

嘗試使用hibernate.show_sql = true來打印查詢並確認延遲加載是否正常工作:

   <bean id= "entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean" >
         ...
         <property name="jpaProperties" >
               <props>
                     ...
                     <prop key="hibernate.show_sql" >true</ prop>
                     <prop key="hibernate.format_sql" >true</ prop>
                     <prop key="hibernate.use_sql_comments">true</prop>
          ...

use_sql_comments特別重要,因為它將在查詢開始時打印注釋,說明寫查詢的原因:一對多,命名查詢名稱,條件查詢文本等。

然后,通過放置斷點,可以查看在使用調試器檢查集合時是否已獲取該集合。

如果不是這種情況,並且沒有調用getter,則可能是通過直接訪問屬性neurologicalFindingList直接在類內部觸發了延遲加載。

您是否直接在PatientEntity內部訪問屬性,例如以equals和hashcode訪問? 如果是這樣,則通過從等號和哈希碼中刪除它來解決問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM