簡體   English   中英

延遲加載對象集合以使用HQL插入

[英]Lazy loading collection of objects for insert with HQL

我需要通過HQL從數據庫加載對象的集合,目的是僅將這些對象用於在某些新記錄中設置關聯。

考慮以下幾點:我需要向所有nr> 50的學生發送電子郵件,並且需要跟蹤傳輸中包括的所有收件人。

首先選擇學生:

Query query = sessionFactory.getCurrentSession().createQuery("from Student student left join fetch student.scores where student.credits>50");
List<Student> students = query.list();

這將返回一個學生列表,其中包含為每條記錄加載的所有列(非關聯屬性,例如名字,姓氏,出生日期...)。 問題是,當我有大量數據時,由於大量無用的數據從db傳輸到應用程序服務器,因此上面的查詢非常慢並且占用大量內存。 我不能將所有屬性直接延遲加載到實體中,因為這會殺死應用程序的其他區域。

我需要的是一種僅使用我在使用對象時獲取的ID來加載上述集合的方法,只是將它們設置為關聯中的一些新對象。 我知道可以輕松完成OneToMany關聯,但是如何直接查詢集合呢?

List<Recipient> emailRecipients = new ArrayList<>();
for(Student student: students){
   Recipient rec = new Recipient();

   //this is the only usage of the student object
   rec.setStudent(student);
   ...
   set other properties for the recipient
   sessionFactory.getCurrentSession().save(rec);
}

在接收者內部,學生對象的設置如下:

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "STD_ID", nullable = false)
private Student student;

如您所見,僅需要Student對象的id,但是我不知道該怎么做。

您可以使用一個特定於Hibernate的技巧,即使您沒有提供實際的受管實體,也可以使用該技巧來設置FK關聯。 假設我們有一個StudentId,我們可以簡單地設置:

Student student = new Student();
student.setId(studentId);
rec.setStudent(student);

標准JPA不支持此功能,但可與Hibernate一起使用。 只需確保您沒有從子級到父級的任何級聯傳播(無論如何,就不應該這樣)。

最后,我僅加載了studentId,並修改了接收者內部的映射,使其也包括了studentId:

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "STD_ID", insertable=false, updatable = false)
private Student student;

@Column(name = "STD_ID", nullable = false)
private Long studentId;

現在我可以簡單地設置studentId,並且性能會更好。

暫無
暫無

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

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