主表对象:
@Entity
@Table(name = "master")
public class Master implements Serializable {
@Id
@GeneratedValue
@Column(name = "id")
private int id;
@Column(name = "name")
private String name;
@OneToMany
@JoinColumns({
@JoinColumn(updatable = false, insertable = false, name = "name", referencedColumnName = "name"),
@JoinColumn(updatable = false, insertable = false, name = "id", referencedColumnName = "id")
})
private Set<Child> chld= new HashSet<Child>(0);
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Set<Child> getChld() {
return chld;
}
public void setChld(Set<Child> chld) {
this.chld= chld;
}
}
子表对象:
@Entity
@Table(name = "temptest")
public class TableObject implements Serializable {
@Column(name = "name")
private String name;
@Id
@GeneratedValue
@Column(name = "p_id")
private int p_id;
@Column(name = "id")
private String id;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getP_id() {
return p_id;
}
public void setP_id(int p_id) {
this.p_id = p_id;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
内部加入代码:
Criteria cr1 = session.createCriteria(Master.class, "m");
cr1.createAlias("chld", "c", Criteria.INNER_JOIN);
List list = cr1.list();
Master m= (Master) list.get(0);
System.out.println("Master name>" + m.getName());
Set set = m.getChld();
System.out.println("set count" + set.size());
Iterator it = set.iterator();
while (it.hasNext()) {
Child chld= (Child ) it.next();
System.out.println("chld name"+chld.getName());
}
当我运行此代码时,会形成内部联接查询并返回结果集。
14:31:09,343 INFO [STDOUT] Hibernate: select this_.name as name189_1_, this_.id
as id189_1_, c1_.p_id as p1_188_0_, c1_.id as id188_0_, c1_.name as name188_
0_ from master this_ inner join child c1_ on this_.name=c1_.name and thi
s_.id=c1_.id
在Master对象中消耗了结果。但问题是,在检索Master对象内部可用的Child对象时。
Set set = m.getChld();
再次触发选择查询以从子表中获取记录
14:31:09,343 INFO [STDOUT] Hibernate: select chld0_.name as name189_1_, chld0
_.id as id189_1_, chld0_.p_id as p1_1_, chld0_.p_id as p1_188_0_, chld0_.id a
s id188_0_, chld0_.name as name188_0_ from child chld0_ where chld0_.name=
? and chld0_.id=?
请咨询,这是Hibernate的正常行为还是我在这里缺少任何东西,