【问题标题】:Hibernate fetching parent/child object as a row instead of parent with collection objHibernate将父/子对象作为一行而不是带有集合obj的父对象
【发布时间】:2016-12-18 07:52:46
【问题描述】:

获取中的问题。 我有A类和B类 表A、B

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 : 一个 db 有 2 条记录

  1. A 的 id 为 1 -> 有 B(table) 的 2 条记录
  2. A 的 id 为 2 -> 有 B(table) 的 3 条记录

当我使用 hql/jpql 查询时,如下所示: Query query = entityManager.createQuery("SELECT a from A a join fetch a.bs"); 列表列表 = 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() 方法加载父对象的集合数据。

【问题讨论】:

    标签: java hibernate


    【解决方案1】:

    如果您查看 JPA 规范,第 4.4.5.3 节,一个示例如下:

    SELECT d FROM Department d JOIN FETCH d.employees
    

    在这种情况下,虽然可能只存在 1 个 Department 和多个 Employee 关联,但查询结果将返回多行,每行对应关联数量的 Employee 连接,尽管只有一个 @987654325 @。

    换句话说,JPA 规范不要求这样的查询消除重复。

    为了获得 2 个 A 实体及其集合的精确列表,您需要修改查询以包含 DISTINCT子句。

    SELECT distinct a FROM A a JOIN FETCH a.bs
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-01-04
      • 1970-01-01
      • 2011-11-17
      • 2017-11-23
      • 2017-10-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多