2013-06-23 15 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); 
    }