1

我目前正在努力使用 JPA Criteria API 创建查询。我想动态构建我的查询。使用元模型和类型化查询对我来说是没有选择的。假设我有以下实体:

@Entity
@Table(name = "MYENTITY")
public class MyEntity {
...
    @OneToMany(mappedBy = "myEntity", fetch = FetchType.LAZY)
    private Set<MyRelatedEntity> myRelatedEntities;
...
}

@Entity
@Table(name = "MYRELATEDENTITY")
public class MyRelatedEntity {
...
    @ManyToOne
    @JoinColumn(name = "MYENTITY", nullable = false)
    private MyEntity myEntity;
...
}

我尝试通过加入“MyEntity”来查询“MyRelatedEntity”中的字段:

    CriteriaBuilder builder = em.getCriteriaBuilder();
    CriteriaQuery<Object[]> query = builder.createQuery(Object[].class);
    Root<MyEntity> root = query.from(MyEntity.class);
    root.join("myRelatedEntities");
    query.select(builder.array(root.get("myRelatedEntities").get("name")));
    Query queryCriteria = em.createQuery(query);
    List<Object[]> resultRows = queryCriteria.getResultList();

resultRows 是一个空列表,尽管直接在数据库上的以下查询给了我结果:

Select myrelent.name from MYENTITY myent, MYRELATEDENTITY myrelent where myent.id = myrelent.myentity;

使用条件 API 构建的查询有什么问题?任何帮助表示赞赏!

4

1 回答 1

1

您不需要指示 CriteriaBuilder 返回一个数组:它无论如何都会做正确的工作。因此,只需将返回类型更改为 String 和 select 语句:

CriteriaQuery query = builder.createQuery(String.class);
Root<MyEntity> root = query.from(MyEntity.class);
query.select(root.get("myRelatedEntities").get("name"));
Query queryCriteria = em.createQuery(query);
List<String> resultRows = queryCriteria.getResultList();

不相关:关于加入,建立加入的标准方法是:

Join<MyEntity, MyRelatedEntity> related = root.join("myRelatedEntities");
query.select(related.get("name"));

However it's good to know that your way works altogether!

于 2013-11-04T16:55:02.210 回答