获取中的问题。 我有A级和B级 表A,B
CLASS A:
private Integer id;
private String name;
private Set<B> bs = new HashSet<B>(0);
public A() {
}
public A(String name, Set<B> bs) {
this.name = name;
this.bs = bs;
}
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", unique = true, nullable = false)
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
@Column(name = "name", length = 45)
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
@OneToMany(fetch = FetchType.LAZY, mappedBy = "a")
public Set<B> getBs() {
return this.bs;
}
public void setBs(Set<B> bs) {
this.bs = bs;
}
CLASS B:
private Integer id;
private A a;
private String BName;
public B() {
}
public B(A a){
this.a = a;
}
public B(A a, String BName) {
this.a = a;
this.BName = BName;
}
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", unique = true, nullable = false)
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "a_id", nullable = false)
public A getA() {
return this.a;
}
public void setA(A a) {
this.a = a;
}
@Column(name = "b_name", length = 45)
public String getBName() {
return this.BName;
}
public void setBName(String BName) {
this.BName = BName;
}
IN DB:数据库有2条记录
当我使用hql / jpql查询时如下: 查询查询= entityManager.createQuery(&#34;从A中选择a a a fetch a.bs&#34;); List list = query.getResultList();
我在列表中获得了5条记录,而不是2条带有相关子级的记录。
而不是获得: 1. A1-> B集合, 2.A2-> B集合
我不希望size()方法加载父对象的收集数据。
答案 0 :(得分:0)
如果您查看JPA规范,第4.4.5.3节,就像这样的例子:
SELECT d FROM Department d JOIN FETCH d.employees
在这种情况下,虽然可能只存在1个Department
和多个Employee
关联,但查询结果将返回多行,每行都包含相关数量的Employee
联接,尽管存在只是一个Department
。
换句话说,JPA规范不要求像这样的查询消除重复。
为了获取填充了其集合的2个A
实体的精确列表,您需要修改查询以包含DISTINCT
子句。
SELECT distinct a FROM A a JOIN FETCH a.bs