Hibernate/SQL在不返回关联的情况下检索记录
问题描述:
我想从表中检索记录,但没有在实体中提及其关联。如何使用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;
}
}
答
在getAssociatedBreeds()方法的@OneToMany注释中,将fetch属性设置为EAGER。将此更改为LAZY。这会导致您的关联元素在您实际访问它们之前不会被加载。
我以前试过,它仍然执行数据库上的查询。我也不会在数据库上执行什么查询,因为我也想在数据库的查询执行上保存一些性能。 – mandy 2012-03-23 17:54:46
您的任何代码是否调用getAssociatedBreeds()方法?或者你的Animal实体以某种方式被序列化,也许是因为它们被发送到远程UI层? – nansen 2012-03-23 18:07:09
我在调试模式下运行测试,当findByCriteria发生时,此时本身我看到日志和查询已执行以检索相关记录。现在,如果请求完成,在完成之前有一个getAssociatedBreeds调用。在这种情况下,UI层没有序列化发生。 – mandy 2012-03-23 18:50:56