2012-03-23 117 views
0

我想從表中檢索記錄,但沒有在實體中提及其關聯。如何使用Hibernate做到這一點?Hibernate/SQL在不返回關聯的情況下檢索記錄

我想在動物表中獲取記錄而不嘗試在下面的示例中檢索品種。

下面是我協會有:

@Entity 
@Table(name = "ANIMAL") 
public class Animal { 
private Long id; 
private String type; 
private String subtype; 
private String category;  
private Set<Breed> associatedBreeds = new HashSet<Breed>(); 

@Id 
@Column(name = "ID") 
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "idSeq") 
@SequenceGenerator(name = "idSeq", sequenceName = "ID_SEQ") 
public Long getId() { 
    return id; 
} 

@Column(name = "TYPE") 
public String getType() { 
    return type; 
} 

@Column(name = "SUBTYPE") 
public String getSubtype() { 
    return subtype; 
} 

public void setId(Long id) { 
    this.id = id; 
} 

public void setType(String type) { 
    this.type = type; 
} 

public void setSubtype(String subtype) { 
    this.subtype = subtype; 
} 

public void setCategory(String category) { 
    this.category = category; 
} 

@Column(name = "CATEGORY", insertable = false, updatable = false) 
public String getCategory() { 
    return category; 
} 

@OneToMany(mappedBy = "propertyUsage", fetch = FetchType.EAGER, cascade = { CascadeType.ALL }) 
public Set<Breed> getAssociatedBreeds() { 
    return associatedBreeds; 
} 

public void setAssociatedBreeds(
     Set<Breed> associatedFinancials) { 
    this.associatedBreeds = associatedBreeds; 
} 
} 

@Entity 
@Table(name = "Breed") 
public class Breed { 
private Long id; 

private Animal animal; 

@Id 
@Column(name = "ID") 
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "idSeq1") 
@SequenceGenerator(name = "idSeq1", sequenceName = "ID_SEQ1") 
public Long getId() { 
    return id; 
} 

public void setPropertyUsage(PropertyUsage propertyUsage) { 
    this.animal = animal; 
} 

@ManyToOne 
@JoinColumn(name="ANIMAL_ID", referencedColumnName="ID")  
public PropertyUsage getAnimal() { 
    return animal; 
} 

}

回答

1

在getAssociatedBreeds()方法的@OneToMany註釋中,將fetch屬性設置爲EAGER。將此更改爲LAZY。這會導致您的關聯元素在您實際訪問它們之前不會被加載。

+0

我以前試過,它仍然執行數據庫上的查詢。我也不會在數據庫上執行什麼查詢,因爲我也想在數據庫的查詢執行上保存一些性能。 – mandy 2012-03-23 17:54:46

+0

您的任何代碼是否調用getAssociatedBreeds()方法?或者你的Animal實體以某種方式被序列化,也許是因爲它們被髮送到遠程UI層? – nansen 2012-03-23 18:07:09

+0

我在調試模式下運行測試,當findByCriteria發生時,此時本身我看到日誌和查詢已執行以檢索相關記錄。現在,如果請求完成,在完成之前有一個getAssociatedBreeds調用。在這種情況下,UI層沒有序列化發生。 – mandy 2012-03-23 18:50:56

1

更改取類型懶惰取= FetchType.LAZY這將使休眠不拉的品種直到它們被請求或使用,而不是當動物物體被創建時

+0

我以前試過,它仍然執行數據庫上的查詢。我也不會在數據庫上執行什麼查詢,因爲我也想在數據庫的查詢執行上保存一些性能。 – mandy 2012-03-23 17:54:57

+0

我使用LAZY工作並延遲了連接關閉。感謝您的迴應和幫助。 – mandy 2012-03-26 21:07:08

相關問題