2016-12-05 89 views
0

比方說,我有一個類A(與表tbl_a映射)和一個類B(映射表tbl_b)。例如,這兩個類(表)具有關係OneToMany的關係。 類B也與另一個類C(表tbl_c)有關係。例如,該關係也是OneToMany。 我通過Hibernate Criteria在表tbl_a上查詢(選擇查詢)。當我在控制檯中檢查休眠生成的SQL時,我看到類A,類B,甚至類C的所有屬性。 即使一切運行良好,查詢也很大,選擇所有這些屬性(列)可能會影響性能。 我不希望類BC的所有屬性。我只想要類A的屬性。 在Hibernate中是否有配置,不選擇相關表的所有屬性? 注意:使用默認的Lazy fetchType。瞭解由休眠生成的sql查詢

+1

讀了大約一個叫預先加載的東西:-)通常情況下,表將只有當你要求他們加載。除非你將它們標記爲急切加載。 通常急切的加載雖然更好,性能明智,但不記憶明智。 – Tschallacka

回答

0

如果我們能看到你寫的代碼會更好。然而,會盡量給擡起頭

@Entity 
 
@Table(name="a") 
 
public class A{ 
 

 
@Id 
 
@column(name="id") 
 
@GeneratedValue(Strategy=GenerationType.AUTO) 
 
private int id; 
 

 
// suppose this class is mapped to class B as many to one 
 
@ManyToOne(Fetch=FetchType.EAGER) 
 
@JoinColumn(name="b_id") 
 
private B b; 
 
//Note that it is advisable to keep many to one relationships fetch type as eager. Though it depends on project architecture. Performance wise it fetches only one instance in memory this class is mapped to. 
 

 

 
//getter setters 
 

 
} 
 

 
@Entity 
 
@Table(name="b") 
 
public class B{ 
 

 
@Id 
 
@column(name="id") 
 
@GeneratedValue(Strategy=GenerationType.AUTO) 
 
private int id; 
 

 
@OneToMany(fetch=FetchType.LAZY, mappedBy="b",Cascade=CascadeType.ALL) 
 
private Set<A> allA = new HashSet<A>(); 
 
//this says that keep a onetomany relationship but do not fetch any of the associated entities until said so. Which is advisable as because If we keep FetchType.EAGER then it will fetch more than one entity for a single entity. 
 
Suppose B entity is related to 10 A entities then it will load all of them as soon as B is fetched in memory, so it will be a performance issue for a semi large application also. 
 

 
//getter setter 
 

 
}