【问题标题】:JPA2 select list from entityJPA2 从实体中选择列表
【发布时间】:2016-11-01 15:33:27
【问题描述】:

我有一个带有 oneToMany 的 JPA 映射,现在我想用 CriteriaQuery 选择这个集合,就像

query.select(Root_.collection).where(cb.equal(root.id, id))
List<ResultObject> results = em.createQuery(query).getResultList();

我无法想象这根本不可能......因为从存储库中它也是可能的......

这种情况的用例是将多个查询的结果放在 DTO 中。

谢谢!

【问题讨论】:

  • 运行该代码sn-p的结果是什么?首先想到的是FetchType。您是否将 OneToMany 集合的 fetchtype 设置为 Eager
  • 这是一个惰性获取,因为我不想加载所有集合,当我们不需要它们时

标签: java spring-data-jpa jpa-2.0


【解决方案1】:

不允许在 select 子句 中使用集合,所以这个 query.select(Root_.collection) 在 Criteria API 中不起作用。

您可以这样做,但不推荐使用方法 (http://www.kumaranuj.com/2013/07/jpa-2-fetch-joins-and-whether-we-should.html):

    root.fetch(Root_.collection);
    query.select(root).distinct(true).where(cb.equal(root.get("id"), id));

然后根据上面返回的不同 Root 行的数量,您现在可以访问根中 oneToMany 关系的集合,如下所示:

    final Root result = em.createQuery(query).getSingleResult(); //Since we are getting results using primary key and distinct, we then use getSingleResult
    final Collection rootCollection = result.getCollection();

这里的重点在于root.fetch(Root_.collection)select(root).distinct(true)的使用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-25
    • 1970-01-01
    • 2015-05-30
    • 2013-01-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多