【问题标题】:JPQL : geting results from a multi expression selectJPQL:从多表达式选择中获取结果
【发布时间】:2013-06-20 00:11:02
【问题描述】:

这是我的 JPQL 查询:

SELECT p, 
   exists( select dp from DocumentPublication dp where dp.documentVersion = p) 
FROM 
   DocumentVersion p where document.id = :id

获取结果的代码如下:

   Query query =   
     getEntityManager().createNamedQuery("DocumentVersion.findByDocumentId");

   query.setParameter("id", docsFilter.getProjectId());

   List<Object[]>  res;
   try
   {
       res = query.getResultList();
   }
   catch (NoResultException e)
   {
       return null;
   }
   // res only contains a list of DocumentVersion / No 'boolean'

我想检索结果列表,但是当我对查询执行“getResultList”时,我只看到选择的第一部分(DocumentVersion 列表),没有看到我想要的布尔值得到。

我正在使用最新的休眠版本之一作为持久性提供程序。

谢谢。

【问题讨论】:

  • 您应该添加调用此查询的 Java 代码
  • :-(... 不应该问你这个问题。我一直在浏览并发现stackoverflow.com/questions/6804077/…;简而言之exists 是条件语句的一部分,并且只是@ 的一部分987654325@ 或 HAVING 子句(检查答案中提供的链接)。很抱歉给您带来不便。
  • @SJuan76 不要感到抱歉。你帮了我。谢谢 :)

标签: jpa jpql


【解决方案1】:

正如 SJuan 指出的,exist() 不能在 select 表达式中使用。所以我用左连接更改了查询,效果很好。这是查询:

SELECT p, count(dp.id) 
FROM DocumentVersion p left join  p.documentPublications dp 
where p.document.id  = :id 
group by p.id

使用代码检索结果:

 List<Object[]>  res;
   try
   {
       res = query.getResultList();
   }
   catch (NoResultException e)
   {
       return null;
   }

   List<DocumentVersion> documentVersions = new ArrayList<>();
   for(Object[] objects : res)
   {
      DocumentVersion documentVersion = (DocumentVersion) objects[0];
      documentVersion.setPublished( (Long) objects[1] >  0);
      documentVersions.add( documentVersion );
   }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-12-02
    • 1970-01-01
    • 2011-08-24
    • 1970-01-01
    • 2016-11-14
    • 2020-11-22
    • 2016-05-27
    • 1970-01-01
    相关资源
    最近更新 更多