我想从表中检索记录而没有实体中提到的关联。如何使用Hibernate做到这一点?
我想在Animal表中获取记录而不尝试在下面的示例中检索Breed。
以下是我的协会:
@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;
}
}
答案 0 :(得分:1)
将获取类型更改为lazy fetch = FetchType.LAZY这将使hibernate在请求或使用它们之前不会拉出类型,而不是在创建Animal对象时
答案 1 :(得分:1)
在getAssociatedBreeds()方法的@OneToMany注释中,将fetch属性设置为EAGER。将此更改为LAZY。这将导致您的相关元素在您实际访问它们之前不会被加载。