理解Hibernate

时间:2016-12-05 13:15:33

标签: java hibernate hibernate-mapping hibernate-criteria

假设我有一个类A(用表tbl_a映射)和一个类B(用表tbl_b映射)。例如,这两个类(表)具有关系OneToMany关系。 类B也与另一个类C(表tbl_c)有关系。例如,该关系也是OneToMany。 我通过Hibernate Criteria在表tbl_a上进行查询(选择查询)。当我在控制台中检查hibernate生成的sql时,我会看到类A,类B甚至类C的所有属性。 即使一切运行良好,查询也很大,选择所有这些属性(列)可能会影响性能。 我不想要课程BC的所有属性。我只想要类A的属性。 Hibernate中是否有配置,不选择相关表的所有属性? 注意:使用默认的Lazy fetchType。

1 个答案:

答案 0 :(得分: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

}