2013-06-23 18 views
0

这里是我的JPQL查询: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”时,我只能看到select(DocumentVersion的列表)的第一部分,我没有看到我想要得到的布尔值。

我正在使用最新的hibernate版本之一作为pesistence提供者。

谢谢。

+0

你应该添加调用此查询 – SJuan76

+0

@ SJuan76做:) – unludo

+1

Java代码: - (...应有没有问你,我一直在浏览和发现http://stackoverflow.com/questions/6804077/is-select-exists-possible-in-jpql;简而言之'存在'是条件语句的一部分,只有成为'WHERE'或'HAVING'条款的一部分(查看答案中提供的链接),对不便之处敬请谅解。 – SJuan76

回答

1

正如SJuan指出的,exists()不能用于选择表达式。所以我改变了查询与左连接运作良好。下面是该查询:

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); 
    }