我面临着n + 1个选择查询的奇怪问题。我的映射看起来像这样:
@Entity
@IdClass(MyTablePK.class)
@Table(name = "my_table", schema = "schema")
public class MyTable {
@Id
@Column(name = "name", nullable = false, length = 12)
private String name="";
@Id
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "myStringValue", referencedColumnName = "myStringValue")
private AdditionalData data;
... (other fields, getters, setters)
}
public class MyTablePK implements Serializable {
private String name;
private AdditionalData data;
(getters,setters)
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
MyTablePK that = (MyTablePK) o;
if (name!= null ? !name.equals(that.name) : that.name!= null) return false;
return !(data!= null ? !data.equals(that.data) : that.data!= null);
}
@Override
public int hashCode() {
int result = name!= null ? name.hashCode() : 0;
result = 31 * result + (data!= null ? data.hashCode() : 0);
return result;
}
}
@Entity
@Table(name = "info", schema = "schema")
public class AdditionalData implements Serializable {
@Id
@Column(name = "recno")
private Long recno;
@Column(name = "info1", length = 3)
private String info1;
@Column(name = "info2", length = 3)
private String info2;
... (getters, setters)
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
AdditionalData data = (AdditionalData) o;
return recno.equals(data.recno);
}
@Override
public int hashCode() {
return recno.hashCode();
}
}
现在,我从MyTable中选择所有值。正如预期的那样,我得到n + 1个选择,对于每个MyTable行,一个新的AdditionalData查询到达。为了打架,我写了一个连接获取查询:
FROM MyTable mytab join fetch mytab.data
然而......并没有改变任何事情。
现在,有趣的是,如果我暂时忽略业务需求,并删除@IdClass使name
成为唯一的@Id - 一切正常,所有数据都通过单个查询获得。这是为什么?我不能用复合id的一部分来对抗n + 1选择吗?
如果它是相关的 - 我使用Hibernate 4.3.5.Final和Oracle数据库
答案 0 :(得分:0)
这可能与此处的已知问题有关:https://hibernate.atlassian.net/browse/HHH-10292
尝试将myStringValue列映射两次。在加入列中加入String
,另一次加入AdditionalData
时加入insertable = false, updatable = false
。