2011-08-24 59 views
10

我想在兩個表之間創建一個使用HQL(Hibernate查詢語言)的聯合。該SQL腳本工作正常,我的SQL服務器上:如何在HQL中執行聯合SQL語句?

SELECT COUNT(DISTINCT linkedin_id) as test, school_name 
FROM 
(SELECT * FROM alum_education 
UNION 
SELECT * FROM alum_connection_educations) AS UNIONS where school_name='some string' 

的問題是,當我嘗試Grails中這樣運行:

 def countOfEdu = AlumEducation.executeQuery("select count (distinct linkedinId) as countOfEdu, schoolName as SchoolName from (SELECT * FROM alumEducation UNION SELECT * FROM alumConnectionEducations) AS UNIONS where schoolName='some string'") 

我得到這個錯誤:

org.hibernate.hql.ast.QuerySyntaxException: unexpected token: (near line 1, column 83 [select count(distinct linkedinId) as countOfEdu, schoolName as SchoolName from (SELECT * FROM alumEducation UNION SELECT * FROM alumConnectionEducations) AS UNIONS where schoolName='Duquesne University'] 

如何在grails中運行上面的SQL語句?

感謝 傑森

+3

可能重複:http://stackoverflow.com/questions/201023/hibernate-union-alternatives –

+0

刪除評論 – jellobird

回答

37

工會不被HQL支持。在Hibernate的JIRA中有一個issue,自2005年開放。

+0

但被「複製** [HHH-3971](https://hibernate.atlassian.net/browse/HHH-3971)在休眠**中使用UNION ALL,INTERSECTION功能「,並關閉 –

0

就你而言,真正的問題是子查詢在EJBQL的FROM子句中不受支持。

0

我想分享一下我發現的方式來避免這種情況。這裏唯一的規則是有相同的類型,在這種情況下一個字符串,對應於返回列表的類型,只要你想,你可以添加許多表:

public List<String> findByCPForCNPJ(String query){ 
TypedQuery<String> ccpf = manager.createQuery("select cpf from PessoaFisica where cpf like :pCpf", String.class); 
ccpf.setParameter("pCpf", "%" + query + "%"); 
List<String> lista1 = ccpf.getResultList(); 

TypedQuery<String> ccnpj = manager.createQuery("select cnpj from PessoaJuridica where cnpj like :pCnpj", String.class); 
ccnpj.setParameter("pCnpj", "%" + query + "%"); 

lista1.addAll(ccnpj.getResultList()); 
return lista1; 
} 

我在Java中使用的方法此解決方案。 我希望我已經貢獻了一下,運氣好所有...