2016-12-18 63 views
0

獲取中的問題。 我有類A和B 表A,BHibernate將父/子對象作爲一行而不是收集對象的父對象

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; 
} 

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個記錄

  1. A有id 1 - >有2條記錄B(表)
  2. A具有ID 2 - >有3個記錄B(表)的

當我的查詢用HQL/JPQL象下面這樣: 查詢查詢= entityManager.createQuery(「選擇一個來自A的聯接取一個。 BS「); List list = query.getResultList();

我在列表中得到了5條記錄,而不是2條與關聯的孩子。

  1. A1 - > B1
  2. A1 - > B2
  3. A2 - > B3
  4. A2 - > B4
  5. A2 - > B5

,而不是領: 1 A1-> B收藏, 2. A2-> B收藏

我沒有需要size()方法來加載父對象的集合數據。

回答

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