0

我不明白如何加入 eclipse 链接与标准。这是我的实体:

public class A implements Serializable {

  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  @Basic(optional = false)
  @Column(name = "id")
  private Long id;
  @Column(name = "value")
  private String value;   

  @OneToMany(mappedBy = "aid")
  private Collection<B> bCollection; 
}

public class B implements Serializable {

  @Id      
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  @Basic(optional = false)
  @Column(name = "id")
  private Long id;

  @JoinColumn(name = "a_id", referencedColumnName = "id")
  @ManyToOne
  private A aid;  
}

我这样做:

    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery cq = cb.createQuery();
    Root<A> a = cq.from(A.class);
    Join<A, B> j = a.join("aid",JoinType.INNER);
    cq.distinct(true);
    //and now what?        
    cq.where(cb.equal(a.get("id"), "aid"));
    Object r = em.createQuery(cq).getResultList();

现在,如何将我的 join 子句绑定到 CriteriaQuery?

4

2 回答 2

1

首先,为了获得包含来自 A 和 B 的所有字段的结果列表,您需要将结果塑造为Tuples 列表或 s 列表,Object本文所述(投影结果章节)。

这需要使用多选语句或使用如下构造

cq.multiselect(a, b));
cq.select(cb.construct(a, b));

其中 b 应该像这样获得:

CollectionJoin<A, B> b = a.join(A_.bCollection, JoinType.INNER);  // using Metamodel
于 2012-10-23T15:29:16.750 回答
0

如果您想要的只是“从 A 中选择 a 并加入 a.bCollection”,从而只返回带有 B 的 As,那么您只需要:

CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery cq = cb.createQuery();
Root<A> a = cq.from(A.class);
Join<A, B> j = a.join("bcollection",JoinType.INNER);
cq.distinct(true);
Object r = em.createQuery(cq).getResultList();

JPA 将使用 B 的辅助属性上定义的关系为您创建 A->B 表连接,因此您不需要。返回的 A 将是完整的,除了由于您在 bCollection 映射上使用默认获取类型,Bs 可能会延迟获取。如果您希望它们在单个查询中急切地引入并关联到 As,请使用 fetch 方法而不是 join:

a.fetch("bcollection",JoinType.INNER);
于 2012-10-23T18:51:27.170 回答